堆排序

 

package HeapSort

// 使用堆排序查询出找出堆里面最大的数
func HeapSortMax(arr []int, length int) []int {
    //length := len(arr)
    if length <= 1 {
        return arr
    }
    depth := length/2 - 1
    // 从最底部一个二叉树开始找
    for i := depth; i >= 0; i-- {
        topMax := i
        leftNode := 2*i + 1
        rightNode := 2*i + 2
        if leftNode < length && arr[leftNode] > arr[topMax] {
            topMax = leftNode
        }
        if rightNode < length && arr[rightNode] > arr[topMax] {
            topMax = rightNode
        }
        if i != topMax {
            arr[i], arr[topMax] = arr[topMax], arr[i]
        }
    }
    return arr
}

func HeapSort(arr []int) []int {
    length := len(arr)
    // 这里是找出最大的放在最后面
    for i := 0; i < length; i++ {
        lastLen := length - i
        HeapSortMax(arr, lastLen)
        
        arr[0], arr[lastLen-1] = arr[lastLen-1], arr[0]
      
    }
    return arr
}
原文地址:https://www.cnblogs.com/shiwenhu/p/13122055.html