Sorting 堆索引示例说明
这段代码取自Go heap示例,带有我自己添加的打印。这是操场。 大多数事情都很简单,也很有意义,但有一件事我不能概括,那就是为什么main中堆的索引0上的“minimum”print返回值1,即正确的最小值,但在堆的pop函数中打印4返回1 see输出 如果堆的根最小值始终为n=0,为什么在pop函数本身中为n=4?然后,它似乎工作良好,按降序排列 有人能解释一下这是怎么回事吗?在我明白发生了什么事之前,我对实现类似于流行音乐的东西感到不舒服Sorting 堆索引示例说明,sorting,go,data-structures,heap,Sorting,Go,Data Structures,Heap,这段代码取自Go heap示例,带有我自己添加的打印。这是操场。 大多数事情都很简单,也很有意义,但有一件事我不能概括,那就是为什么main中堆的索引0上的“minimum”print返回值1,即正确的最小值,但在堆的pop函数中打印4返回1 see输出 如果堆的根最小值始终为n=0,为什么在pop函数本身中为n=4?然后,它似乎工作良好,按降序排列 有人能解释一下这是怎么回事吗?在我明白发生了什么事之前,我对实现类似于流行音乐的东西感到不舒服 // This example demonstr
// This example demonstrates an integer heap built using the heap interface.
package main
import (
"container/heap"
"fmt"
)
// An IntHeap is a min-heap of ints.
type IntHeap []int
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) {
// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
fmt.Printf("n: %v\n", n)
fmt.Printf("x: %v\n", x)
return x
}
// This example inserts several ints into an IntHeap, checks the minimum,
// and removes them in order of priority.
func main() {
h := &IntHeap{2, 1, 5}
heap.Init(h)
heap.Push(h, 3)
fmt.Printf("minimum: %d\n", (*h)[0])
for h.Len() > 0 {
fmt.Printf("roll: %d\n", (*h)[0])
fmt.Printf("%d\n", heap.Pop(h))
}
}
教科书中的堆算法包括一种修复堆的方法,如果您知道整个堆结构是正确的,那么在Olg n时间内,除了根错误之外,对于所有n个界中的堆,都是正确的a[n] 您还可以使用它来实现。假设您有一个数组int[4],您正在尝试排序。取一个切片s int[]=a,len=4,cap=4,然后: 如果镜头==1,则停止。 交换s[0]和s[lens-1]。 将切片缩小一个项目:s=阵列,len=lens-1,cap=caps。 如果堆出现故障,请修复它。 转到1。 假设您的示例以[1,2,5,3]开头。然后:
[1, 2, 5, 3]
[3, 2, 5, 1] Swap first and last
[3, 2, 5], 1 Shrink slice by one
[2, 3, 5], 1 Correct heap invariant
[5, 3, 2], 1 Swap first and last
[5, 3], 2, 1 Shrink slice by one
[3, 5], 2, 1 Correct heap invariant
[5, 3], 2, 1 Swap first and last
[5], 3, 2, 1 Shrink slice by one
5, 3, 2, 1 Sorted (descending order)
太棒了,谢谢你。这个算法叫什么?a[n]
[1, 2, 5, 3]
[3, 2, 5, 1] Swap first and last
[3, 2, 5], 1 Shrink slice by one
[2, 3, 5], 1 Correct heap invariant
[5, 3, 2], 1 Swap first and last
[5, 3], 2, 1 Shrink slice by one
[3, 5], 2, 1 Correct heap invariant
[5, 3], 2, 1 Swap first and last
[5], 3, 2, 1 Shrink slice by one
5, 3, 2, 1 Sorted (descending order)