Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Quicksort the Swift way
var list = [8,1,55,34,13,8,5,0,1,3,2,21]
func quicksort1(list:[Int]) -> [Int] {
if list.count == 0 {
return []
}
let pivotValue = list[0]
let smaller = filter(list, { $0 < pivotValue })
smaller
let greater = filter(list, { $0 > pivotValue })
greater
return quicksort1(smaller) + Array(arrayLiteral:pivotValue) + quicksort1(greater)
}
quicksort1(list)
func quicksort2(list:[Int]) -> [Int] {
if list.count == 0 {
return []
}
let pivotValue = list[0]
let listStripped = list.count > 1 ? list[1...list.count-1] : []
let smaller = filter(listStripped, { $0 <= pivotValue })
let greater = filter(listStripped, { $0 > pivotValue })
return quicksort2(smaller) + Array(arrayLiteral:pivotValue) + quicksort2(greater)
}
quicksort2(list)
func quicksort(list:[Int]) -> [Int] { return countElements(list) == 0 ? [] : quicksort(filter(list.count > 1 ? list[1...list.count-1] : [], { $0 <= list[0] })) + Array(arrayLiteral: list[0]) + quicksort(filter(list.count > 1 ? list[1...list.count-1] : [], { $0 > list[0] })) }
quicksort(list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment