快排(swift)

伪代码如下:

/**
 
 quickSort(array) {
 
 quickSort_private(array, 0, array.size-1)
   
 }

 //p,r分别代表数组的起始和终止下标,0和length-1
 quickSort_private(array, p, r) {
 //递归调用,只剩一个元素的时候返回。作为终止条件
 if p>=r return;

 let middle = partion(array, p, r)//分区的值
 quicksort_private(array, p, middle-1)//排左边
 quicksort_private(array, middle+1, r)//排右边
 
 }
 
//
 partion(array, left, right) {
 let pivot = array[right]
 var i = left
 for j in left..

实践代码如下:

public func sort(_ sourceArr: inout [Int]){
    quickSort(&sourceArr, 0, sourceArr.count-1)
}

private func quickSort(_ sourceArr: inout [Int], _ left: Int, _ right: Int) {
    guard left < right else {return}
    
    let q = partion(&sourceArr, left, right)
    quickSort(&sourceArr, left, q-1)
    quickSort(&sourceArr, q+1, right)
    
}

//分区函数
private func partion(_ sourceArr: inout [Int], _ left: Int, _ right: Int) -> Int {
    let pivot = sourceArr[right]
    var i = left
    for j in left..
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

你可能感兴趣的:(快排(swift))