//堆排序
func heapSort(data Interface, a, b int) {
first := a
lo := 0
hi := b - a
// Build heap with greatest element at top.
//构建堆结构,最大的元素的顶部,就是构建大根堆
for i := (hi - 1) / 2; i >= 0; i-- {
siftDown(data, i, hi, first)
}
// Pop elements, largest first, into end of data.
//把first插入到data的end结尾
for i := hi - 1; i >= 0; i-- {
data.Swap(first, first+i) //数据交换
siftDown(data, lo, i, first) //堆重新筛选
}
}
// siftDown implements the heap property on data[lo, hi).
// first is an offset into the array where the root of the heap lies.
func siftDown(data Interface, lo, hi, first int) {
//hi为数组的长度
//这里有一种做法是把跟元素给取到存下来,但是为了方法更抽象,省掉了这部,取而代之的是在swap的时候进行相互交换
root := lo //根元素的下标
for {
child := 2*root + 1 //左叶子结点下标
//控制for循环介绍,这种写法更简洁,可以查看我写的堆排序的文章
if child >= hi {
break
}
//防止数组下标越界,判断左孩子和右孩子那个大
if child+1 < hi && data.Less(first+child, first+child+1) {
child++
}
//判断最大的孩子和根元素之间的关系
if !data.Less(first+root, first+child) {
return
}
//如果上面都 满足,则进行数据交换
data.Swap(first+root, first+child)
root = child
}
}
这个包中还有很多方法,这个包实现了很多方法,比如排序反转,二分搜索。排序通过 quickSort()这个方法来控制该调用快排还是堆排。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易采站长站的支持。










