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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
| void counting_sort_stable(int arr[], int n) { if (n <= 1) return; int min_val, max_val; find_range(arr, n, &min_val, &max_val); int range = max_val - min_val + 1; int* count = (int*)calloc(range, sizeof(int)); int* output = (int*)malloc(n * sizeof(int)); printf("稳定计数排序过程:\n"); for (int i = 0; i < n; i++) { count[arr[i] - min_val]++; } printf("频次统计: "); for (int i = 0; i < range; i++) { if (count[i] > 0) { printf("%d:%d ", i + min_val, count[i]); } } printf("\n"); for (int i = 1; i < range; i++) { count[i] += count[i - 1]; } printf("累积计数: "); for (int i = 0; i < range; i++) { if (count[i] > 0) { printf("%d:%d ", i + min_val, count[i]); } } printf("\n"); printf("\n构建过程:\n"); for (int i = n - 1; i >= 0; i--) { int val = arr[i]; int pos = count[val - min_val] - 1; output[pos] = val; count[val - min_val]--; printf("元素 %d 放置到位置 %d\n", val, pos); } for (int i = 0; i < n; i++) { arr[i] = output[i]; } free(count); free(output); }
typedef struct { int value; char id; } StableElement;
void print_stable_elements(StableElement arr[], int n, const char* title) { printf("%s: ", title); for (int i = 0; i < n; i++) { printf("(%d,%c) ", arr[i].value, arr[i].id); } printf("\n"); }
void counting_sort_stable_elements(StableElement arr[], int n) { if (n <= 1) return; int min_val = arr[0].value, max_val = arr[0].value; for (int i = 1; i < n; i++) { if (arr[i].value < min_val) min_val = arr[i].value; if (arr[i].value > max_val) max_val = arr[i].value; } int range = max_val - min_val + 1; int* count = (int*)calloc(range, sizeof(int)); StableElement* output = (StableElement*)malloc(n * sizeof(StableElement)); for (int i = 0; i < n; i++) { count[arr[i].value - min_val]++; } for (int i = 1; i < range; i++) { count[i] += count[i - 1]; } for (int i = n - 1; i >= 0; i--) { int val = arr[i].value; int pos = count[val - min_val] - 1; output[pos] = arr[i]; count[val - min_val]--; } for (int i = 0; i < n; i++) { arr[i] = output[i]; } free(count); free(output); }
void test_counting_sort_stability() { printf("=== 计数排序稳定性测试 ===\n"); StableElement arr[] = { {4, 'A'}, {2, 'B'}, {2, 'C'}, {4, 'D'}, {1, 'E'}, {2, 'F'} }; int n = sizeof(arr) / sizeof(arr[0]); print_stable_elements(arr, n, "排序前"); counting_sort_stable_elements(arr, n); print_stable_elements(arr, n, "排序后"); printf("分析: 相同值的元素保持原有顺序,计数排序是稳定的\n\n"); }
|