基数排序
作者:互联网
1 #include <stdio.h> 2 3 const int pow10[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000}; 4 5 #define get_digit(num, n) ((num) % pow10[(n)] / pow10[(n) - 1]) 6 7 int counting_sort(const int *arr, int size, int *target, int n) { 8 int count[10] = {0}; 9 for (int i = 0; i < size; ++i) { 10 count[get_digit(*(arr + i), n)]++; 11 } 12 if (count[0] == size) { 13 return 0; 14 } 15 for (int i = 1; i < 10; ++i) { 16 count[i] += count[i - 1]; 17 } 18 for (int i = size - 1; i >= 0; --i) { 19 *(target + *(count + get_digit(*(arr + i), n)) - 1) = *(arr + i); 20 --*(count + get_digit(*(arr + i), n)); 21 } 22 return 1; 23 } 24 25 void radix_sort(int *arr, int size) { 26 int another[size]; 27 int state = 1, i; 28 for (i = 1; state > 0 && i <= 10; ++i) { 29 if (i % 2 > 0) { 30 state = counting_sort(arr, size, another, i); 31 } else { 32 state = counting_sort(another, size, arr, i); 33 } 34 } 35 if (i % 2 > 0 && i <= 10) { 36 for (int j = 0; j < size; ++j) { 37 arr[j] = another[j]; 38 } 39 } 40 } 41 42 int main() { 43 int arr[] = {329, 457, 657, 839, 436, 720, 355}; 44 const int size = sizeof(arr) / sizeof(int); 45 radix_sort(arr, size); 46 for (int i = 0; i < size; ++i) { 47 printf("%d\n", arr[i]); 48 } 49 return 0; 50 }
注:基数排序数组元素不能为负,若存在负数可进行偏置处理。
如[3, -2, 4]的所有元素偏置+2,变成[5, 0, 6],基数排序之后再用-2偏置回来。
标签:count,sort,arr,int,state,基数排序,size 来源: https://www.cnblogs.com/zhangshiyu/p/16439135.html