golang的container/heap包是否有效地执行堆排序?

huangapple go评论64阅读模式
英文:

Is golang container/heap effectively doing heap sort?

问题

golang的container/heap包在底层切片上是否有效地执行堆排序?

看起来底层数组并不总是有序。

type IntHeap []int
// ... 其他接口实现
func main() {
    a := []int{}
    h := IntHeap(a)
    heap.Init(&h)
    heap.Push(&h, 3)
    heap.Push(&h, 2)
    heap.Push(&h, 5)
    // 底层数组 'a' 并不是有序的
    fmt.Printf("a: %+v\n", a)
}
英文:

Is golang container/heap effectively doing heap sort on an underlying slice?

It doesn't look like underlying array is always sorted.

type IntHeap []int
// ... other interface implementation
func main() {
    a := []int{}
	h := IntHeap(a)
	heap.Init(&h)
	heap.Push(&h, 3)
    heap.Push(&h, 2)
    heap.Push(&h, 5)
    // underlying array 'a' is not sorted
    fmt.Printf("a: %+v\n", a)
}

答案1

得分: 3

底层数组不需要排序。它只是堆实现中使用的二叉树的表示。

此外,堆不使用堆排序。堆排序是使用堆对数组进行排序的一种方法。

func main() {
    a := []int{}
    h := IntHeap(a)
    heap.Init(&h)
    heap.Push(&h, 3)
    heap.Push(&h, 2)
    heap.Push(&h, 5)

    // 堆排序
    for h.Len() > 0 {
        fmt.Printf("%d ", heap.Pop(&h))
    }
    // 输出: 2 3 5
}
英文:

The underlying array doesn't have to be sorted. It just represent the binary tree used by heap implemention.

Also heaps don't use heapsort. Heapsort is a way to sort an array using heap.

func main() {
    a := []int{}
    h := IntHeap(a)
    heap.Init(&h)
    heap.Push(&h, 3)
    heap.Push(&h, 2)
    heap.Push(&h, 5)

    // heapsort
    for h.Len() > 0 {
		fmt.Printf("%d ", heap.Pop(&h))
	}
    // output: 2 3 5
}

huangapple
  • 本文由 发表于 2022年7月22日 11:08:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/73074701.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定