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
| int partition_randomized(int arr[], int low, int high) { int random_index = low + rand() % (high - low + 1); swap(&arr[random_index], &arr[high]); return partition_lomuto(arr, low, high); }
int median_of_three(int arr[], int low, int high) { int mid = low + (high - low) / 2; if (arr[mid] < arr[low]) { swap(&arr[low], &arr[mid]); } if (arr[high] < arr[low]) { swap(&arr[low], &arr[high]); } if (arr[high] < arr[mid]) { swap(&arr[mid], &arr[high]); } swap(&arr[mid], &arr[high]); return partition_lomuto(arr, low, high); }
void insertion_sort_range(int arr[], int low, int high) { for (int i = low + 1; i <= high; i++) { int key = arr[i]; int j = i - 1; while (j >= low && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } }
void quick_sort_optimized(int arr[], int low, int high) { if (low < high) { if (high - low < 10) { insertion_sort_range(arr, low, high); return; } int pi = median_of_three(arr, low, high); quick_sort_optimized(arr, low, pi - 1); quick_sort_optimized(arr, pi + 1, high); } }
void quick_sort_tail_recursive(int arr[], int low, int high) { while (low < high) { if (high - low < 10) { insertion_sort_range(arr, low, high); return; } int pi = median_of_three(arr, low, high); if (pi - low < high - pi) { quick_sort_tail_recursive(arr, low, pi - 1); low = pi + 1; } else { quick_sort_tail_recursive(arr, pi + 1, high); high = pi - 1; } } }
void test_optimized_quick_sort() { printf("=== 优化版本测试 ===\n"); const int size = 20; int original[size]; srand(time(NULL)); for (int i = 0; i < size; i++) { original[i] = rand() % 50; } int arr1[size], arr2[size], arr3[size]; memcpy(arr1, original, sizeof(original)); memcpy(arr2, original, sizeof(original)); memcpy(arr3, original, sizeof(original)); printf("原始数组: "); for (int i = 0; i < size; i++) printf("%d ", original[i]); printf("\n\n"); printf("标准快速排序结果: "); quick_sort_basic(arr1, 0, size - 1, 0); for (int i = 0; i < size; i++) printf("%d ", arr1[i]); printf("\n"); printf("优化快速排序结果: "); quick_sort_optimized(arr2, 0, size - 1); for (int i = 0; i < size; i++) printf("%d ", arr2[i]); printf("\n"); printf("尾递归优化结果: "); quick_sort_tail_recursive(arr3, 0, size - 1); for (int i = 0; i < size; i++) printf("%d ", arr3[i]); printf("\n\n"); }
|