go 堆排序

本文介绍了如何使用堆数据结构实现建堆、堆化操作,以及堆排序算法,并通过示例展示了在优先队列中的实际应用。从funcleft和funcright定义的整数运算开始,深入探讨了如何维护最大堆结构,最后通过main函数展示了整个过程的完整流程。
摘要由CSDN通过智能技术生成

func left(i int) int {
return 2*i + 1
}

func right(i int) int {
return 2*i + 2
}

//建堆
func buildHeap(a []float64) {
length := len(a)
for i := length / 2; i >= 0; i-- {
maxHeap(i, a, length)
}
}

//堆化,保证每个父节点都大于子节点
func maxHeap(p int, a []float64, length int) {
l := left§
r := right§
index := p
if l < length && a[l] > a[index] {
index = l
}
if r < length && a[r] > a[index] {
index = r
}
if index != p {
a[index], a[p] = a[p], a[index]
maxHeap(index, a, length)
}
}

func main(){
a := []int{1, 5, 6, 4, 7, -8, 77, -9, 6, 1, 0, 3}
buildHeap(a)
fmt.Println(a)
length := len(a)
//堆排,父节点是最大的,每次将父节点放到最后一个元素,再将剩余元素堆化
for length > 0 {
a[0], a[length-1] = a[length-1], a[0]
length–
maxHeap(0, a, length)
}
fmt.Println(a)
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您解答有关golang实现堆排序的问题。在golang中,可以使用container/heap包来实现堆排序。具体实现步骤如下: 1. 定义一个类型用于表示需要排序的元素。这个类型需要实现container/heap包中的heap.Interface接口。 2. 通过实现heap.Interface接口中的Less方法来定义元素之间的比较方式。 3. 定义一个堆结构体,它拥有一组需要排序的元素。 4. 在堆结构体上定义Len、Less和Swap方法,这些方法实现heap.Interface接口中的方法。 5. 实现Push和Pop方法,它们是heap.Interface接口中的方法。 6. 使用堆结构体的Push和Pop方法来进行堆排序。 这是一个简单的golang实现堆排序的示例代码: package main import ( "container/heap" "fmt" ) 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{}) { *h = append(*h, x.(int)) } func (h *IntHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } func main() { h := &IntHeap{2, 1, 5, 4, 3} heap.Init(h) fmt.Printf("Before heap sort: %v\n", h) heap.Sort(h) fmt.Printf("After heap sort: %v\n", h) } 在这个示例代码中,我们定义了一个IntHeap类型来表示需要进行堆排序的元素。它实现了heap.Interface接口中的Less方法。我们还定义了一个堆结构体,它拥有一个IntHeap类型的变量。在Push和Pop方法中,我们分别使用append和切片操作来实现堆的操作。在main函数中,我们创建了一个IntHeap类型的变量h,并使用heap.Init方法来初始化它。然后,我们使用heap.Sort方法来对其进行堆排序。最终的输出结果是:Before heap sort: &[2 1 5 4 3] After heap sort: &[1 2 3 4 5]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值