sunjunior 2020-05-10
思路:
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 < half { var childIndex = (tmpIndex << 1) + 1; var child = array[childIndex] let rightIndex = childIndex + 1 if rightIndex < heapSize, array[rightIndex] > child { childIndex = rightIndex child = array[childIndex] } if ele >= child { break } array[tmpIndex] = child tmpIndex = childIndex } array[tmpIndex] = ele } }
* 最好、最坏、平均时间复杂度:O(nlogn)
* 空间复杂度: O(1)
* 稳定性: 不稳定
要知道时间复杂度只是描述一个增长趋势,复杂度为O的排序算法执行时间不一定比复杂度为O长,因为在计算O时省略了系数、常数、低阶。实际上,在对小规模数据进行排序时,n2的值实际比 knlogn+c还要小。