Skip to content

Instantly share code, notes, and snippets.

@simonbromberg
Last active July 6, 2016 18:01
Show Gist options
  • Save simonbromberg/07a69d96ff4dc7d00f01835bf47abbbc to your computer and use it in GitHub Desktop.
Save simonbromberg/07a69d96ff4dc7d00f01835bf47abbbc to your computer and use it in GitHub Desktop.
Quicksort playground
import Darwin
func quickSort(inout data:[Int], _ left:Int, _ right:Int) {
let index = partition(&data, left, right)
if left < index - 1 {
quickSort(&data, left, index - 1)
}
if index < right {
quickSort(&data, index, right)
}
}
func quickSort(inout data:[Int]) {
quickSort(&data, 0, data.count - 1)
}
func partition(inout data:[Int], _ left:Int, _ right:Int) -> Int {
let upto = UInt32(right - left + 1)
let pivotRand:Int = Int(arc4random_uniform(upto)) + left
// let pivot = (right + left) / 2
let pivotVal = data[pivotRand]
var leftT = left
var rightT = right
while leftT <= rightT {
while data[leftT] < pivotVal {
leftT += 1
}
while data[rightT] > pivotVal {
rightT -= 1
}
if leftT <= rightT {
swap(&data, leftT, rightT)
leftT += 1
rightT -= 1
}
}
return leftT
}
func swap(inout data:[Int], _ left:Int, _ right:Int) {
let leftVal = data[left]
data[left] = data[right]
data[right] = leftVal
}
// Test with some random data
var data = [Int]()
let max = 10
let maxVal = 100
for i in 0..<max {
let sign = arc4random_uniform(2) == 0 ? -1 : 1
data += [sign * Int(arc4random_uniform(UInt32(100)))]
}
print(data)
quickSort(&data)
print(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment