I’d like to know how can write an efficient version of quicksort where list is partitioned in one pass.
I’ve this fragment of code,
let rec quicksort' = function
[] -> []
| x::xs -> let small = List.filter (fun y -> y < x ) xs
and large = List.filter (fun y -> y > x ) xs
in quicksort' small @ (x :: quicksort' large);;
but here I’m going through the list more than 1 time (calling 2 times quicksort for small and large) .
The idea is to do it in just one step without going to the list more than 1 time.
List.partition is the way to go:
Notice that
List.partitionhelps avoid one redundant traversal throughxs. You still have to sort the smaller part and the larger part recursively since it’s the way Quicksort works.I have to say that this version of
quicksortis far from efficient. Quicksort algorithm is an inherent in-place algorithm which mutates an input array recursively. Another factor is pivot selection; choosing the first element as the pivot is not always a good idea.These factors lead to an extremely different implementation for efficiency (probably using
Arrayand mutation). Quicksort onListshould be used for demonstrating the idea of the algorithm and the beauty of its recursion.