排序算法-堆排序
2021-01-24 19:14
标签:hal rev size psi 时间 swift 复杂 mpi nlogn 思路: * 最好、最坏、平均时间复杂度:O(nlogn) * 空间复杂度: O(1) * 稳定性: 不稳定 排序算法-堆排序 标签:hal rev size psi 时间 swift 复杂 mpi nlogn 原文地址:https://www.cnblogs.com/tzsh1007/p/12731420.html堆排序(升序为例)
1. 首先要建一个大顶堆
2. 交换堆顶元素与最后一个元素,堆的size - 1
3. 重复第二步,直至堆中只有元素一个class HeapSort {
var array = [5, 7, 2, 8, 9, 4, 7, 3, 2]
var heapSize: Int!
init() {
heapSize = array.count
}
func sort() {
for i in (0 ... (heapSize >> 1) - 1).reversed() {
siftDown(index: i)
}
while heapSize > 1 {
heapSize -= 1
let tmp = array[0]
array[0] = array[heapSize]
array[heapSize] = tmp
siftDown(index: 0)
}
}
// 将数组转成堆
private func siftDown(index: Int) {
var tmpIndex = index
let ele = array[tmpIndex]
let half = heapSize >> 1
while tmpIndex child {
childIndex = rightIndex
child = array[childIndex]
}
if ele >= child { break }
array[tmpIndex] = child
tmpIndex = childIndex
}
array[tmpIndex] = ele
}
}
上一篇:一维数组的创建及使用