Skip to content

Instantly share code, notes, and snippets.

@chefnobody
Created March 18, 2018 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chefnobody/7a694907326a18ab98a03ccbe19efcfd to your computer and use it in GitHub Desktop.
Save chefnobody/7a694907326a18ab98a03ccbe19efcfd to your computer and use it in GitHub Desktop.
A Quick Sort implementation in Swift
//: Playground - noun: a place where people can play
import UIKit
extension Array where Element: Comparable {
mutating func quickSort() -> Array<Element> {
// Recursive function that works out where our next pivots will be.
func qSort(start startIndex: Int, _ pivot: Int) {
if (startIndex < pivot) {
// Sort value at pivot into place.
let iPivot = qPartition(start: startIndex, pivot)
qSort(start: startIndex, iPivot - 1)
qSort(start:iPivot + 1, pivot)
}
}
// Start Quick Sort at beginnig of list and set pivot to the end.
qSort(start: 0, self.endIndex - 1)
return self
}
// Sort the selected pivot value into the correct index/position
// Manages the Wall, Current and Pivot index comparisons.
mutating func qPartition(start startIndex: Int, _ pivot: Int) -> Int {
var wallIndex: Int = startIndex
// Compare range with pivot, bubble values WRT to the pivot value
// to below or above that value.
for currentIndex in wallIndex..<pivot {
if self[currentIndex] <= self[pivot] {
if wallIndex != currentIndex {
self.swapAt(currentIndex, wallIndex)
}
// Move the wall forward.
wallIndex += 1
}
}
// Finally swap the value at the pivot with the value at the wall
if wallIndex != pivot {
self.swapAt(wallIndex, pivot)
}
return wallIndex
}
}
var numbers = [7,2,1,6,8,5,3,4]
let results = numbers.quickSort()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment