堆排序是一個效能很優的排序演算法,一般藉助資料結構——最大堆,來實現排序的效果,一般步驟為:建堆——排序,建堆和排序的過程中都夾雜著保持堆的穩定性。優先順序隊列也用到資料結構堆,主要C語言演算法如下:
#include <stdio.h>#include <limits.h>//記錄最大堆的長度unsigned int heap_size = 0;//下標從0開始//求父節點的下標unsigned int parent(unsigned int index){return (index - 1) / 2;}//求左兒子節點的下標unsigned int lchild(unsigned int index){return 2 * index + 1;}//求右兒子節點的下標unsigned int rchild(unsigned int index){return 2 * index + 2;}//保持最大堆的有序性void max_heapify(int *A, unsigned int i){unsigned int l, r, largest;inttemp;largest = i;l = lchild(i);r = rchild(i);if (l < heap_size && A[l] > A[i]){largest = l;}if (r < heap_size && A[r] > A[largest]){largest = r;}if (i != largest){temp = A[i];A[i] = A[largest];A[largest] = temp;max_heapify(A, largest);}}//建立最大堆void build_max_heap(int *A){int i;//最後往前,不是葉子的結點開始遍曆for (i = heap_size / 2 - 1; i >= 0; i--){max_heapify(A, i);}}void heap_sort(int *A){int temp;int i;build_max_heap(A);for (i = heap_size - 1; i >= 0; i--){temp = A[0];A[0] = A[i];A[i] = temp;heap_size--;max_heapify(A, 0);}}//返回堆中最大最大值int heap_maximum(int *A){return A[0];}//移除堆中的最大值int heap_extract_max(int *A){int max;if (heap_size < 1){fprintf(stderr, "heap underflow");}max = A[0];A[0] = A[heap_size - 1];heap_size--;max_heapify(A, 0);return max;}//將堆中某一項的值增大到key,i的取值為0到heap_size-1void heap_increase_key(int *A, unsigned int i, int key){int temp;if (key < A[i]){fprintf(stderr, "new key is smaller than current key");}A[i] = key;while (i > 1 && A[parent(i)] < A[i]){temp = A[i];A[i] = A[parent(i)];A[parent(i)] = temp;i = parent(i);}}void max_heap_insert(int *A, int key){heap_size++;A[heap_size - 1] = INT_MIN;heap_increase_key(A, heap_size - 1, key);}int main(){int array[] = {5, 10, 2, 3, 9, -1, 3};unsigned int i;heap_size = sizeof(array) / sizeof(int);heap_sort(array);for (i = 0; i < sizeof(array) / sizeof(int); i++){printf("%d ", array[i]);}return 0;}