List.partition is the way to go:
let rec quicksort = function | [] -> [] | x::xs -> let smaller, larger = List.partition (fun y -> y < x) xs in quicksort smaller @ (x::quicksort larger)
Note that List.partition
helps avoid one redundant crawl through xs
. You still have to sort the smaller part and the larger part recursively, since this works with Quicksort.
I have to say that this version of quicksort
is far from efficient. Quick Sort Algorithm is a built-in algorithm that recursively mutates an input array. Another factor is the choice of vertices; choosing the first element, since the anchor point is not always a good idea.
These factors lead to extremely different implementation implementations (possibly using Array
and mutation). Quicksort on a List
should be used to demonstrate the idea of ββan algorithm and the beauty of its recursion.
source share