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
| #include <stdio.h> #include <stdlib.h> #include <string.h>
int get_digit(int num, int d) { for (int i = 0; i < d; i++) { num /= 10; } return num % 10; }
void counting_sort_for_radix(int arr[], int n, int digit_pos) { int output[n]; int count[10] = {0}; for (int i = 0; i < n; i++) { count[get_digit(arr[i], digit_pos)]++; } for (int i = 1; i < 10; i++) { count[i] += count[i - 1]; } for (int i = n - 1; i >= 0; i--) { int digit = get_digit(arr[i], digit_pos); output[count[digit] - 1] = arr[i]; count[digit]--; } for (int i = 0; i < n; i++) { arr[i] = output[i]; } }
void radix_sort(int arr[], int n) { int max_val = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max_val) { max_val = arr[i]; } } for (int digit_pos = 0; max_val / pow(10, digit_pos) > 0; digit_pos++) { counting_sort_for_radix(arr, n, digit_pos); } }
int main() { int arr[] = {170, 45, 75, 90, 2, 802, 24, 66}; int n = sizeof(arr) / sizeof(arr[0]); printf("原数组: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); radix_sort(arr, n); printf("排序后: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); return 0; }
|