package main import "fmt" //堆的特性 //1.是完全二叉树 //2.每一个节点都大于子节点(大堆) //3.根节点最大 //4.左子节点2i+1, 由子节点2i+2, 父节点(i-1)/2 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) int{ length := len(heap) for i := length/2 - 1; i >= 0; i-- { maxHeap(heap, i, length) } return length } func maxHeap(heap []int, i int, length int) { 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] //需要继续比较起父节点 maxHeap(heap, largest, length) } } func main() { a := []int{3,31,3,54,5,6,7,34,2,213} heapLength := buildHeap(a) for i := len(a) - 1; i > 0; i-- { a[i], a[0] = a[0], a[i] // 把第一个数字 是最大的 和最后一个交换 最后一个就 i不断减少 最后的 倒数第二 倒数第三 不断是当前最大的数字 heapLength-- maxHeap(a, 0, heapLength) } fmt.Println(a) }