package main
import "fmt"
func main() {
array := []interface{}{4, 2, 8, 5, 1, 9, 6, 11, 0, 4, 2, 9, 7, 3, 12, 43, 23, 12, 0, 97, 4}
headSoft(array, func(a, b interface{}) bool {
a1 := a.(int)
a2 := b.(int)
return a1 <= a2
})
fmt.Println(array)
}
func headSoft(array []interface{}, cmp func(a, b interface{}) bool) {
len := len(array)
//建堆
for i := (len / 2) - 1; i >= 0; i-- {
adjustHeap(array, i, len, cmp)
}
//排序
for i := 0; i < len; i++ {
sz := len - i - 1
array[0], array[sz] = array[sz], array[0]
adjustHeap(array[0:sz], 0, sz, cmp)
}
}
func adjustHeap(array []interface{}, i, len int, cmp func(a, b interface{}) bool) {
for ch := i<<1 + 1; ch < len; ch = i<<1 + 1 {
rg := i<<1 + 2
if rg < len && cmp(array[ch], array[rg]) {
ch = rg
}
if cmp(array[ch], array[i]) {
return
}
array[ch], array[i] = array[i], array[ch]
i = ch
}
}
网友评论