Skip to content

Instantly share code, notes, and snippets.

@johnazariah
Last active August 29, 2015 14:17
Show Gist options
  • Save johnazariah/e1eff6845a2ee60235ba to your computer and use it in GitHub Desktop.
Save johnazariah/e1eff6845a2ee60235ba to your computer and use it in GitHub Desktop.
Quick-Select & Quick-Sort in F#
// 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