Skip to content

Instantly share code, notes, and snippets.

@go-cristian
Created August 21, 2016 15:02
Show Gist options
  • Save go-cristian/61d76ad98ad03a061eff05f9f16ceea4 to your computer and use it in GitHub Desktop.
Save go-cristian/61d76ad98ad03a061eff05f9f16ceea4 to your computer and use it in GitHub Desktop.
func partition<T: Comparable>(inout array: [T], first: Int, last: Int) -> Int {
let pivot = first
let pivotVal = array[pivot]
(array[first], array[pivot]) = (array[pivot], array[first])
var i = first + 1
var j = first + 1
while j < last {
if array[j] < pivotVal {
(array[i], array[j]) = (array[j], array[i])
i += 1
}
j += 1
}
(array[i-1], array[first]) = (array[first], array[i-1])
return (i - 1)
}
func quicksort<T: Comparable>(inout array: [T], first: Int, last: Int) {
if last-first<1 {return}
let pivot = partition(&array, first: first, last: last)
quicksort(&array, first: first, last: pivot)
quicksort(&array, first: pivot+1, last: last)
}
var list = [ 3,9,8,4,6,10,2,5,7,1]
quicksort(&list, first: 0, last: list.count)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment