MCPcopy
hub / github.com/greyireland/algorithm-pattern / HeapSort

Function HeapSort

src/sort/heap_sort.go:3–18  ·  view source on GitHub ↗
(a []int)

Source from the content-addressed store, hash-verified

1package sort
2
3func HeapSort(a []int) []int {
4 // 1、无序数组a
5 // 2、将无序数组a构建为一个大根堆
6 for i := len(a)/2 - 1; i >= 0; i-- {
7 sink(a, i, len(a))
8 }
9 // 3、交换a[0]和a[len(a)-1]
10 // 4、然后把前面这段数组继续下沉保持堆结构,如此循环即可
11 for i := len(a) - 1; i >= 1; i-- {
12 // 从后往前填充值
13 swap(a, 0, i)
14 // 前面的长度也减一
15 sink(a, 0, i)
16 }
17 return a
18}
19func sink(a []int, i int, length int) {
20 for {
21 // 左节点索引(从0开始,所以左节点为i*2+1)

Callers 1

TestHeapSortFunction · 0.85

Calls 2

sinkFunction · 0.85
swapFunction · 0.85

Tested by 1

TestHeapSortFunction · 0.68