Go 描述:
// siftDown implements the heap property on data[lo, hi).// first is an offset into the array where the root of the heap lies.func siftDown(data sort.Interface, lo, hi, first int) { root := lo for { child := 2*root + 1 if child >= hi { break } if child+1 < hi && data.Less(first+child, first+child+1) { child++ } if !data.Less(first+root, first+child) { return } data.Swap(first+root, first+child) root = child }}// 堆排序// 将 data 的 [a, b) 范围进行排序func heapSort(data sort.Interface, a, b int) { first := a lo := 0 hi := b - a // Build heap with greatest element at top. for i := (hi - 1) / 2; i >= 0; i-- { siftDown(data, i, hi, first) } // Pop elements, largest first, into end of data. for i := hi - 1; i >= 0; i-- { data.Swap(first, first+i) siftDown(data, lo, i, first) }}
C++ 描述:
#include// siftDown implements the heap property on data[lo, hi).// first is an offset into the array where the root of the heap lies.template void siftDown(T data[], int lo, int hi, int first){ auto root = lo; for (; true;) { auto child = 2 * root + 1; if (child >= hi) { break; } if (child + 1 < hi && data[first + child] < data[first + child + 1]) { ++child; } if (!(data[first + root] < data[first + child])) { return; } std::swap(data[first + root], data[first + child]); root = child; }}// 堆排序// 将 data 的 [a, b) 范围进行排序template void HeapSort(T data[], int a, int b){ auto first = a; auto lo = 0; auto hi = b - a; // Build heap with greatest element at top. for (auto i = (hi - 1) / 2; i >= 0; --i) { siftDown(data, i, hi, first); } // Pop elements, largest first, into end of data. for (auto i = hi - 1; i >= 0; --i) { std::swap(data[first], data[first + i]); siftDown(data, lo, i, first); }}
Python 描述: