From 3594109c970a1dc77bfafb62c05b98defdf4e6dd Mon Sep 17 00:00:00 2001 From: mhs-m <1923153170@qq.com> Date: Wed, 27 May 2026 22:17:52 +0800 Subject: [PATCH] Heap sort builds a max heap from the array, then repeatedly swaps the root (largest) with the last unsorted element and heapifies the reduced heap to sort in place with O(n log n) time. --- Algorithms/C/heap_sort.c | 68 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Algorithms/C/heap_sort.c diff --git a/Algorithms/C/heap_sort.c b/Algorithms/C/heap_sort.c new file mode 100644 index 00000000..366101bd --- /dev/null +++ b/Algorithms/C/heap_sort.c @@ -0,0 +1,68 @@ +// heap_sort.c +// 堆排序(最大堆实现升序) + +#include + +// 交换两个整数 +void swap(int* a, int* b) { + int temp = *a; + *a = *b; + *b = temp; +} + +// 堆化(调整以i为根的子树为最大堆) +// n: 堆的大小, i: 当前节点索引 +void heapify(int arr[], int n, int i) { + int largest = i; // 初始化最大为根 + int left = 2 * i + 1; + int right = 2 * i + 2; + + // 左孩子大于根 + if (left < n && arr[left] > arr[largest]) + largest = left; + + // 右孩子大于当前最大 + if (right < n && arr[right] > arr[largest]) + largest = right; + + // 如果最大值不是根,交换并递归调整 + if (largest != i) { + swap(&arr[i], &arr[largest]); + heapify(arr, n, largest); + } +} + +// 堆排序主函数 +void heap_sort(int arr[], int n) { + // 构建最大堆(从最后一个非叶子节点开始) + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + // 一个个取出元素:将堆顶(最大值)移到数组末尾,再调整剩余堆 + for (int i = n - 1; i > 0; i--) { + swap(&arr[0], &arr[i]); // 当前最大值放到末尾 + heapify(arr, i, 0); // 在缩小后的堆上调整 + } +} + +// 打印数组 +void print_array(int arr[], int size) { + for (int i = 0; i < size; i++) + printf("%d ", arr[i]); + printf("\n"); +} + +// 测试示例 +int main() { + int arr[] = { 12, 11, 13, 5, 6, 7 }; + int n = sizeof(arr) / sizeof(arr[0]); + + printf("原始数组: "); + print_array(arr, n); + + heap_sort(arr, n); + + printf("排序后: "); + print_array(arr, n); + return 0; +} \ No newline at end of file