堆排序
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 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步