Created
January 2, 2015 11:51
-
-
Save burczyk/b4af3bd6ee7e9abcafdb to your computer and use it in GitHub Desktop.
Quicksort the Swift way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
issue here:https://gist.github.com/fjcaetano/b0c00a889dc2a17efad9