Created
December 15, 2016 09:55
-
-
Save sumitokamoi/ae8bd1387306d077c4ce47f24bf2ab21 to your computer and use it in GitHub Desktop.
Haskell style quicksort in Swift
This file contains hidden or 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
quicksort :: (Ord a) => [a] -> [a] | |
quicksort [] = [] | |
quicksort (x:xs) = | |
let smallOrEqual = filter (<= x) xs | |
larger = filter (> x) xs | |
in quicksort smallOrEqual ++ [x] ++ quicksort larger |
This file contains hidden or 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
extension Array { | |
var decompose : (head: Element, tail: [Element])? { | |
return (count > 0) ? (self[0], Array(self[1..<count])) : nil | |
} | |
} | |
func quickSort<T: Comparable>(_ input:[T]) -> [T] { | |
guard let (x, xs) = input.decompose else { return [] } | |
let smallOrEqual = xs.filter { $0 <= x } | |
let larger = xs.filter { $0 > x } | |
return quickSort(smallOrEqual) + Array([x]) + quickSort(larger) | |
} | |
let list = [0, 7, 11, 2, 10, 13, 4, -3, 2, 15, 32, -4, 27] | |
quickSort(list) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment