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 88 89 90 91 92 93 94 95
| #include <stdio.h> #include <stdlib.h> #include <string.h>
void counting_sort(int arr[], int n, int max_value) { int* count = (int*)calloc(max_value + 1, sizeof(int)); int* output = (int*)malloc(n * sizeof(int)); for (int i = 0; i < n; i++) { count[arr[i]]++; } for (int i = 1; i <= max_value; i++) { count[i] += count[i - 1]; } for (int i = n - 1; i >= 0; i--) { output[count[arr[i]] - 1] = arr[i]; count[arr[i]]--; } for (int i = 0; i < n; i++) { arr[i] = output[i]; } free(count); free(output); }
void counting_sort_with_negative(int arr[], int n) { if (n <= 0) return; int max_val = arr[0], min_val = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max_val) max_val = arr[i]; if (arr[i] < min_val) min_val = arr[i]; } int range = max_val - min_val + 1; int* count = (int*)calloc(range, sizeof(int)); int* output = (int*)malloc(n * sizeof(int)); for (int i = 0; i < n; i++) { count[arr[i] - min_val]++; } for (int i = 1; i < range; i++) { count[i] += count[i - 1]; } for (int i = n - 1; i >= 0; i--) { output[count[arr[i] - min_val] - 1] = arr[i]; count[arr[i] - min_val]--; } for (int i = 0; i < n; i++) { arr[i] = output[i]; } free(count); free(output); }
int main() { int arr[] = {4, 2, 2, 8, 3, 3, 1}; int n = sizeof(arr) / sizeof(arr[0]); int max_value = 8; printf("原数组: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); counting_sort(arr, n, max_value); printf("排序后: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); return 0; }
|