1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| #include <stdio.h> #include <stdlib.h> // rand() #include <math.h> // pow()
#define SIZE 5000000 #define VERBOSE_DEBUG 0
static int *get_rand_num_array(int size) { int *p = (int*)malloc(sizeof(int)*size); if(p == NULL) printf("error happened when malloc."); int i; for(i = 0; i < size; i++) { p[i] = rand(); } return p; }
static int test_sorted_nums(int *nums, int size) { int i; for(i = 0; i < size-1; i++) { if(nums[i] > nums[i+1]) { printf("numbers not sorted.\n"); return -1; } } printf("numbers sorted.\n"); return 0; }
static int get_max_length(int *nums, int size) { int max = 1, i; for(i = 0; i < size; i++) { while(nums[i] >= (int)pow(10, max)) max++; } return max; }
void radix_sort(int *nums, int size) { int max = get_max_length(nums, size); int *tmp = (int*)malloc(sizeof(int)*size); int *bucket = (int*)malloc(sizeof(int)*10); int i, j, radix = 1, *p; for(i = 1; i <= max+1; i++) { #if VERBOSE_DEBUG for(j = 0; j < size; j++) printf(" %d ", nums[j]); printf("\n"); #endif memset(bucket, 0, sizeof(int)*10);
for(j = 0; j < size; j++) bucket[(nums[j]/radix)%10]++; for(j = 1; j < 10; j++) { bucket[j] += bucket[j-1]; } for(j = size-1; j >= 0; j--) { tmp[(--bucket[(nums[j]/radix)%10])] = nums[j]; } p = nums; nums = tmp; tmp = p; radix *= 10; } }
int main() { int *nums = get_rand_num_array(SIZE); radix_sort(nums, SIZE); test_sorted_nums(nums, SIZE); free(nums); }
|