Skip to content

Commit

Permalink
add quick sort in swift
Browse files Browse the repository at this point in the history
  • Loading branch information
jerryderry committed Oct 17, 2018
1 parent f52ce43 commit 122e1e7
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
36 changes: 36 additions & 0 deletions swift/12_sorts/QuickSort.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//
// QuickSort.swift
// algo
//
// Created by Wenru Dong on 2018/10/17.
// Copyright © 2018年 Wenru Dong. All rights reserved.
//

import Foundation

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 m = partition(&a, from: low, to: high)
quickSort(&a, from: low, to: a.index(before: m))
quickSort(&a, from: a.index(after: m), 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
}
14 changes: 14 additions & 0 deletions swift/12_sorts/SortsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,20 @@ class SortsTests: XCTestCase {
XCTAssertEqual(a3, [-2, -1, 0, 3, 3, 6, 7, 8, 9, 9])
}

func testQuickSort() {
var a1 = [1, 1, 1, 1]
quickSort(&a1)
XCTAssertEqual(a1, [1, 1, 1, 1])

var a2 = [4, 3, 2, 1]
quickSort(&a2)
XCTAssertEqual(a2, [1, 2, 3, 4])

var a3 = [3, 6, 9, 7, 8, -1, 9, 3, -2, 0]
quickSort(&a3)
XCTAssertEqual(a3, [-2, -1, 0, 3, 3, 6, 7, 8, 9, 9])
}

func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
Expand Down

0 comments on commit 122e1e7

Please sign in to comment.