英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论