Heap sorting can be used as real-time sorting, is the original sort, does not require additional space, time complexity is O (NLGN), the best worst-case average is this, but is not stable ordering, the following is the C language implementation code:
//in order to simplify programming, the first position in a heap array element is not used. struct heap {int size; int *arr;} H;void max_heapify (struct heap * h, int p) {int largest; int hsize = h->size; int left = p * 2; int right = p * 2 + 1; if (left <= hsize && H->arr[left] > h->arr[p]) {largest = left; } else {largest = P; } if (right <= hsize && h->arr[right] > h->arr[largest]) {largest = right; } if (largest! = p) {Swap (& (H->arr[p]), & (H->arr[largest])); Max_heapify (h, largest); }}void build_max_heap (struct heap * h) {int p = h->size/2; while (P >= 1) {max_heapify (H, p--); }}void heap_sort (struct heap *h, int n) {int i; H->size = n; Build_max_heap (h); for (i = 0; i < n; i++) {//always swaps the first element with the last element, noting that the first position in the array does not use Swap (& (H->arr[1]), & (H->arr[h ->size])); h->size--; Max_heapify (H, 1); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Heap Sort C language implementation