QuickSort in swift

2019-04-17  本文已影响0人  枯树恋
public func quickSort<T : RandomAccessCollection & MutableCollection>( _ a : inout T) where T.Element : Comparable {
    quickSort(&a, from: a.startIndex, to: a.index(before: a.endIndex))
}

fileprivate func quickSort<T : RandomAccessCollection & MutableCollection>(_ a : inout T, from low : T.Index, to high : T.Index ) where T.Element : Comparable {
    if low >= high {
        return
    }
    let mid = partition(&a, from: low, to: high)
    quickSor(&a, from: low, to: a.index(before: mid))
    quickSor(&a, from: a.index(after: mid), to: high)
}

fileprivate func partition<T : RandomAccessCollection & MutableCollection>(_ a : inout T, from low: T.Index, to high: T.Index) -> T.Index where T.Element : Comparable {
    let pivot = a[low]
    var j = low
    var i = a.index(after: low)
    
    while i <= high {
        if a[i] < pivot {
            a.formIndex(after: &j)
            a.swapAt(i, j)
        }
        a.formIndex(after: &i)
    }
    a.swapAt(low, j)
    return j
}

public func quicSort<T : RandomAccessCollection & MutableCollection>(_ a : inout T) where T.Element : Comparable {
    quickSort(&a, from: a.startIndex, to: a.index(before: a.endIndex))
}
fileprivate func quickSort<T : RandomAccessCollection & MutableCollection>(_ a : inout T, from low : T.Index, to high : T.Index) where T.Element : Comparable {
    if low >= high {
        return
    }
    
    var i = low
    var j = high
    
    let pivot = a[i]
    
    while i < j {
        while i < j && a[j] >= pivot {
            a.formIndex(before: &j)
        }
        if i < j {
            a[i] = a[j]
        }
        
        while i < j && a[i] <= pivot {
            a.formIndex(after: &i)
        }
        
        if i < j {
            a[j] = a[i]
        }
        
        a[i] = pivot
        quickSort(&a, from: low, to: a.index(before: i))
        quickSort(&a, from: a.index(after: i), to: high)
    }
}
上一篇下一篇

猜你喜欢

热点阅读