排序算法-堆排序

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)

* 稳定性: 不稳定

相关推荐