Created
September 24, 2021 07:52
-
-
Save caryyu/2af526024802c6388db47c1aaae2a225 to your computer and use it in GitHub Desktop.
Algorithm of Heapsort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func main() { | |
var nums []int = []int{57, 40, 38, 11, 13, 34, 48, 75, 6, 19, 9, 7} | |
heapsort(nums) | |
fmt.Println(nums) | |
} | |
func heapsort(nums []int) { | |
sift(nums, len(nums)) | |
for i := len(nums) - 1; i > 0; i-- { | |
var tmp int = nums[0] | |
nums[0] = nums[i] | |
nums[i] = tmp | |
sift(nums, i) | |
} | |
} | |
func sift(nums []int, length int) { | |
for i := length/2 - 1; i >= 0; i-- { | |
var leftI int = 2*i + 1 | |
var rightI int = 2*i + 2 | |
if leftI < length && nums[leftI] > nums[i] { | |
var tmp int = nums[i] | |
nums[i] = nums[leftI] | |
nums[leftI] = tmp | |
} | |
if rightI < length && nums[rightI] > nums[i] { | |
var tmp int = nums[i] | |
nums[i] = nums[rightI] | |
nums[rightI] = tmp | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
参考解释(下述两篇解释不是非常直观,难以理解,凑合看看):
https://juejin.cn/post/6904810712632295432
https://zhuanlan.zhihu.com/p/45725214
要点围绕:
length/2-1 ~ 0
所有非叶子节点范围)0
与length - 1
并排除length - 1
得出新的堆重复调整步骤