美文网首页
QuickSort in swift

QuickSort in swift

作者: 枯树恋 | 来源:发表于2019-04-17 12:02 被阅读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)
    }
}

相关文章

  • QuickSort in swift

  • Sequence in swift

    begin with one quickSort 之前在学习时曾看到swift如此简洁地表达出了快排算法。 时虽叹...

  • java快速排序

    public class QuickSort { public static void quickSort(int...

  • 3.1.0 快速排序

    quicksort

  • Quicksort

    worst-case running time of n2 on an input array of n numb...

  • QuickSort

  • QuickSort

    思想:以第一个为参照元素,分别从第二个和最后一个逐一和参照元素比较,小的留在左边low区域,大的留在右边high区...

  • QuickSort

    快排没啥好讲的,主要是看到剑指offer上说求第K大个数,能达到时间O(N),表示不理解。同时,以下代码中part...

  • QuickSort

  • Quicksort

    Quicksort是一个分而治之的算法,它根据主元把一个大数组分成2个小数组:其中1个数组的元素要比主元小,另一个...

网友评论

      本文标题:QuickSort in swift

      本文链接:https://www.haomeiwen.com/subject/uawgwqtx.html