堆排序(英语:Heapsort)是指利用堆这种数据结构所设计的一种排序算法。堆是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main

import (
    "fmt"
    "math/rand"
    "time"
)

const (
    num      = 10
    rangeNum = 10
)

func main() {
    randSeed := rand.New(rand.NewSource(time.Now().Unix() + time.Now().UnixNano()))
    var buf []int
    for i := 0; i < num; i++ {
        buf = append(buf, randSeed.Intn(rangeNum))
    }
    t := time.Now()

    // 堆排序
    HeapSort(buf)
    fmt.Println(buf)
    fmt.Println(time.Since(t))
}

// 堆排序
func HeapSort(buf []int) {
    temp, n := 0, len(buf)

    for i := (n - 1) / 2; i >= 0; i-- {
        MinHeapFixdown(buf, i, n)
    }

    for i := n - 1; i > 0; i-- {
        temp = buf[0]
        buf[0] = buf[i]
        buf[i] = temp
        MinHeapFixdown(buf, 0, i)
    }
}

func MinHeapFixdown(a []int, i, n int) {
    j, temp := 2*i+1, 0
    for j < n {
        if j+1 < n && a[j+1] < a[j] {
            j++
        }

        if a[i] <= a[j] {
            break
        }

        temp = a[i]
        a[i] = a[j]
        a[j] = temp

        i = j
        j = 2*i + 1
    }
}

  • go run heap.go
1
2
3
4
midoksdeMacBook-Pro:test midoks$ go run heap.go 
[8 8 6 5 2 1 1 1 1 0]
45.2µs