Last active
August 29, 2015 14:17
-
-
Save johnazariah/e1eff6845a2ee60235ba to your computer and use it in GitHub Desktop.
Quick-Select & Quick-Sort in F#
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
// tail-recursive quick-select | |
let select vs k = | |
let rec selectImpl vs k result = | |
match vs with | |
| [] -> result | |
| head :: tail -> | |
let (less, more) = tail |> List.partition ((>=) head) | |
match List.length less with | |
| x when x < k -> selectImpl more (k - x) (less @ result) | |
| x when x > k -> selectImpl less k result | |
| _ -> (less @ result) | |
in selectImpl vs k [] | |
// tail-recursive quick sort in CPS | |
let sort vs = | |
let rec sortImpl vs result cont = | |
match vs with | |
| [] -> cont result | |
| head :: [] -> cont (head :: result) | |
| head :: rest -> | |
let (less, more) = rest |> List.partition ((>=) head) | |
sortImpl more result (fun sortedMore -> | |
sortImpl less (head :: sortedMore) cont) | |
in sortImpl vs [] id | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment