package main
import (
"fmt"
)
func HeapSort(arr []int) []int{
length := len(arr)
for i:=0;i<=length;i++{
lesslength := length-i
HeapSortMax(arr,lesslength)
if i < length{
arr[0],arr[lesslength-1]=arr[lesslength-1],arr[0]
}
}
return arr
}
//堆排序,需要理解逻辑结构和存储结构2*n+1,2*n+2
func HeapSortMax(arr []int,length int) []int{
//length := len(arr)
if length <= 1{
return arr
}
depth := length/2-1
fmt.Println(depth)
for i:=depth;i>=0;i--{
topmax := i
leftchild := 2*i+1
rightchild := 2*i+2
if leftchild <= length-1 && arr[topmax] < arr[leftchild]{
topmax = leftchild
}
if rightchild <= length-1 && arr[topmax] < arr[rightchild]{
topmax = rightchild
}
if i != topmax{
arr[i],arr[topmax]=arr[topmax],arr[i]
}
}
return arr
}
func main(){
arr := []int{232,1,19,11,29, 30, 2, 5, 45, 8, 234, 12, 63}
//fmt.Println(BubblesortMax(arr))
fmt.Println(HeapSort(arr))
}
网友评论