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
| #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h>
void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; }
void heapify(int arr[], int n, int i) { int largest = i; int left = 2 * i + 1; int right = 2 * i + 2; printf(" 调整节点 %d (值=%d)\n", i, arr[i]); if (left < n && arr[left] > arr[largest]) { largest = left; } if (right < n && arr[right] > arr[largest]) { largest = right; } if (largest != i) { printf(" 交换 %d 和 %d (值: %d <-> %d)\n", i, largest, arr[i], arr[largest]); swap(&arr[i], &arr[largest]); heapify(arr, n, largest); } }
void build_max_heap(int arr[], int n) { printf("构建最大堆:\n"); for (int i = n / 2 - 1; i >= 0; i--) { printf("调整子树,根节点索引: %d\n", i); heapify(arr, n, i); printf("当前堆状态: "); for (int j = 0; j < n; j++) { printf("%d ", arr[j]); } printf("\n\n"); } }
void heap_sort_basic(int arr[], int n) { printf("开始堆排序...\n\n"); build_max_heap(arr, n); printf("最大堆构建完成: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n\n"); for (int i = n - 1; i > 0; i--) { printf("第 %d 轮排序:\n", n - i); printf(" 将最大值 %d 移到位置 %d\n", arr[0], i); swap(&arr[0], &arr[i]); printf(" 重新调整堆 (大小=%d)\n", i); heapify(arr, i, 0); printf(" 当前状态: "); for (int j = 0; j < n; j++) { if (j >= i) { printf("[%d] ", arr[j]); } else { printf("%d ", arr[j]); } } printf("\n\n"); } }
void test_basic_heap_sort() { printf("=== 基础堆排序测试 ===\n"); int arr[] = {12, 11, 13, 5, 6, 7}; int n = sizeof(arr) / sizeof(arr[0]); printf("原始数组: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n\n"); heap_sort_basic(arr, n); printf("最终结果: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n\n"); }
|