Ocaml高效快速排序

Ocaml高效快速排序,ocaml,quicksort,Ocaml,Quicksort,我想知道如何编写快速排序的有效版本,其中列表一次分区 我有这段代码 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' lar

我想知道如何编写快速排序的有效版本,其中列表一次分区

我有这段代码

    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);;
let rec quicksort'=函数
[] -> []
|x::xs->let small=List.filter(fun y->yy>x)xs
在快速排序'小@(x::快速排序'大);;
但在这里,我不止一次地浏览了这个列表(无论大小,都调用了两次快速排序)

我们的想法是只需一步就可以完成,而不必多次查看列表

是一条路要走:

let rec quicksort = function
    | [] -> []
    | x::xs -> let smaller, larger = List.partition (fun y -> y < x) xs
               in quicksort smaller @ (x::quicksort larger)
let rec quicksort=函数
| [] -> []
|x::xs->让更小、更大的=List.partition(有趣的y->y
请注意,
List.partition
有助于避免通过
xs
进行一次冗余遍历。您仍然必须递归地对较小的部分和较大的部分进行排序,因为这是快速排序的工作方式

我不得不说,这个版本的
quicksort
远远没有效率。是一种固有的就地算法,递归地改变输入数组。另一个因素是支点选择;选择第一个元素作为轴心并不总是一个好主意


这些因素导致了一种非常不同的效率实现(可能使用
Array
和变异)。应使用
列表上的快速排序来演示算法的思想及其递归的美丽。

如果您需要编写一个有效的排序函数,您可能需要阅读这篇有见地的文章:。除此之外,我敢肯定这本书也写得很好