#include <stdio.h> #include <stdlib.h> #include <time.h> #define SWAP(a, b) do { int __tmp = a; a = b; b = __tmp; } while (0) /* 0 / 1 2 / / 3 4 5 6 left = i*2 + 1 right = i*2 + 2 */ #define LEFT(i) (i*2+1) #define RIGHT(i) (i*2+2) #define LAST_PARENT(heap_size) ((heap_size)/2 - 1) void init_heap(int heap[], int heap_size) { srand((unsigned int)time(NULL)); for (int i = 0; i < heap_size; i++) heap[i] = rand() % 1000; } void print_heap(int heap[], int heap_size) { for (int i = 0; i < heap_size; i++) printf("%d ", heap[i]); printf(" "); } /* 这个函数能保证i节点的子树具有最大堆性质时, 使整个树保持最大堆性质。 */ void max_heapify(int heap[], int i, int heap_size) { int l = LEFT(i); int r = RIGHT(i); int largest; if (l <= (heap_size - 1) && heap[l] > heap[i]) largest = l; else largest = i; if (r <= (heap_size - 1) && heap[r] > heap[largest]) largest = r; if (largest != i) { SWAP(heap[i], heap[largest]); max_heapify(heap, largest, heap_size); } } void min_heapify(int heap[], int i, int heap_size) { int l = LEFT(i); int r = RIGHT(i); int smallest; if (l < heap_size && heap[l] < heap[i]) smallest = l; else smallest = i; if (r < heap_size && heap[r] < heap[smallest]) smallest = r; if (i != smallest) { SWAP(heap[i], heap[smallest]); min_heapify(heap, smallest, heap_size); } } /* 这个函数从堆中最后一个节点的父节点开始, 使左右子树保持最大堆性质。 */ void build_max_heap(int heap[], int heap_size) { for (int i = LAST_PARENT(heap_size); i >= 0; i--) max_heapify(heap, i, heap_size); } void build_min_heap(int heap[], int heap_size) { for (int i = LAST_PARENT(heap_size); i >=0; i--) min_heapify(heap, i, heap_size); } // small --> large void heapsort_max(int heap[], int heap_size) { build_max_heap(heap, heap_size); for (int i = heap_size-1; i > 0; i--) { SWAP(heap[0], heap[i]); heap_size--; max_heapify(heap, 0, heap_size); } } // large --> small void heapsort_min(int heap[], int heap_size) { build_min_heap(heap, heap_size); for (int i = heap_size-1; i > 0; i--) { SWAP(heap[0], heap[i]); heap_size--; min_heapify(heap, 0, heap_size); } } int main(void) { int A[16] = {0}; int heap_size = sizeof(A) / sizeof(A[0]); init_heap(A, heap_size); print_heap(A, heap_size); build_max_heap(A, heap_size); print_heap(A, heap_size); build_min_heap(A, heap_size); print_heap(A, heap_size); heapsort_max(A, heap_size); print_heap(A, heap_size); heapsort_min(A, heap_size); print_heap(A, heap_size); return 0; } /* 运行结果: 201 843 527 779 708 294 908 26 310 995 64 964 507 442 378 40 995 843 964 779 708 527 908 40 310 201 64 294 507 442 378 26 26 40 294 310 64 507 378 779 995 201 708 527 964 442 908 843 26 40 64 201 294 310 378 442 507 527 708 779 843 908 964 995 995 964 908 843 779 708 527 507 442 378 310 294 201 64 40 26 */
参考《算法导论》(第2版)第6章。