其他分享
首页 > 其他分享> > go排序-构建大顶堆

go排序-构建大顶堆

作者:互联网

package main

import "fmt"

func parentNode(i int) int {
	return (i - 1) / 2
}

//左节点
func leftNode(i int) int {
	return 2*i + 1
}

//右节点
func rightNode(i int) int {
	return 2*i + 2
}

//创建heap
func buildHeap(heap []int) {
	length := len(heap)
	for i := length/2 - 1; i >= 0; i-- {
		maxHeap(heap, i, length)
	}
}

// https://www.cnblogs.com/chengxiao/p/6129630.html
// https://www.cnblogs.com/xingyunshizhe/p/11311754.html
func maxHeap(heap []int, i int, length int) {
	fmt.Println(i)
	left := leftNode(i)
	right := rightNode(i)
	largest := 0
	if left < length && heap[left] > heap[i] {
		largest = left
	} else {
		largest = i
	}
	if right < length && heap[right] > heap[largest] {
		largest = right
	}

	if largest != i {
		heap[i], heap[largest] = heap[largest], heap[i]
		// 第一轮排序  从倒数第一个非叶子节点到最后一个开始 把最大的树交换到父节点上  交换会导致新树不符合
		//需要继续比较其父节点 largest这个节点被移动过 所以他要从新进行调整过
		maxHeap(heap, largest, length)
	}
}

func main() {
	a := []int{4,5,2,1,5,6,7,3,2}
	buildHeap(a)
	fmt.Println(a)
}

  

标签:大顶,func,int,length,heap,largest,go,排序,节点
来源: https://www.cnblogs.com/brady-wang/p/15040076.html