Skip to content

Instantly share code, notes, and snippets.

@burczyk
Created January 2, 2015 11:51
Show Gist options
  • Save burczyk/b4af3bd6ee7e9abcafdb to your computer and use it in GitHub Desktop.
Save burczyk/b4af3bd6ee7e9abcafdb to your computer and use it in GitHub Desktop.
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)
@liufsd
Copy link

liufsd commented Mar 24, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment