Merge Sort. Θ(nlgn)

///Merge Sort. O(nlgn)
func mergeSort(array: inout [T]) {
    _mergeSort(array: &array, lower: 0, upper: array.count-1);
}

///Inner representation
func _mergeSort(array: inout [T], lower: Int, upper: Int) {
    guard lower < upper else { return }
    //Note:upper+lower NOT upper-lower
    let divider = (upper+lower)/2
    _mergeSort(array: &array, lower: lower, upper: divider)
    _mergeSort(array: &array, lower: divider+1, upper: upper)
    merge(array: &array, lower: lower, divider: divider, upper: upper)
}

///Core merge algorithm
func merge(array: inout [T], lower: Int, divider: Int, upper: Int) {
    let prefix = Array(array[lower...divider])
    let suffix = Array(array[divider+1...upper])
    //Note:k = lower NOT k = 0
    var i = 0, j = 0, k = lower
    while i

你可能感兴趣的:(Merge Sort. Θ(nlgn))