快速排序

2018-12-18  本文已影响8人  zh_19

快排序的基本思想

快排序(Quick Sort)是一种分治的排序算法。

extension Array where Element: Comparable {
    mutating func partition(left: Index, right: Index) -> Index {
        var i = left + 1
        var j = right
        let pivot = self[left]
        while true {
            // scan right
            while left < j {
                if self[j] > pivot {
                    j -= 1
                } else {
                    break
                }
            }
            
            // scan left
            while i < right {
                if self[i] < pivot {
                    i += 1
                } else {
                    break
                }
            }
            
            if i >= j {
                break
            }
            exchange(i, j: j)
        }
        exchange(left, j: j)
        return j
    }
    mutating func quickSort() {
        quickSort(left: 0, right: count - 1)
    }
    mutating func quickSort(left: Index, right: Index) {
        if left >= right {
            return
        }
        let partitionIndex = partition(left: left, right: right)
        quickSort(left: left, right: partitionIndex - 1)
        quickSort(left: partitionIndex + 1, right: right)
    }
}
上一篇下一篇

猜你喜欢

热点阅读