最小堆排序的實現(Go)

最小堆的特點是其父節點的值不大於任何一個字節點的值, 實現的是升序排序。
最小堆實現排序的原理,構建一個堆,不斷的刪除堆頂,這裏的刪除並不是完全刪除,
而是將堆頂移動到末尾,然後父節點開始下沉操作,最後成爲一個有序序列。

代碼如下:


package main

import "fmt"

func buidHeap(a []int, n int) {

    //heapify from the last parent node
    for i := n / 2; i >= 1; i-- {
        heapifyUpToDown(a, i, n)
    }

}

// 排序索引從1開始的n個元素, 索引爲0的元素不參與排序
func sort(a []int, n int) {
    buidHeap(a, n)

    k := n
    for k >= 1 { // 堆頂移動到最後, 節點進行下沉操作
        a[1], a[k] = a[k], a[1]
        heapifyUpToDown(a, 1, k-1)
        k--
    }
}

// 節點下城
func heapifyUpToDown(a []int, top int, count int) {

    for i := top; i <= count/2; {

        maxIndex := i
        if a[i] < a[i*2] {
            maxIndex = i * 2
        }

        if i*2+1 <= count && a[maxIndex] < a[i*2+1] {
            maxIndex = i*2 + 1
        }

        if maxIndex == i {
            break
        }

        a[i], a[maxIndex] = a[maxIndex], a[i]
        i = maxIndex
    }

}


func main() {
    // 二叉堆排序索引從1開始的n個元素, 數組中的0不參與排序
    arr := []int{0, 2,4,6,8,1, 11}
    sort(arr, len(arr)-1)
    fmt.Print(arr[1:])
}

發佈了63 篇原創文章 · 獲贊 4 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章