Comparing F# with C#: Sorting
https://swlaschin.gitbooks.io/fsharpforfunandprofit/content/posts/fvsc-quicksort.html
如果列表为空,则无事可做。
否则:
1. 取列表的第一个元素
2. 在列表的其余部分找到所有小于第一个元素的元素,并对它们进行排序。
3. 在列表的其余部分中找到所有大于等于第一个元素的元素,并对它们进行排序
4. 将三部分组合在一起得到最终结果:
(已排序的较小元素 + firstElement + 排序较大的元素)let rec quicksort list =
match list with
| [] -> // If the list is empty
[] // return an empty list
| firstElem::otherElements -> // If the list is not empty
let smallerElements = // extract the smaller ones
otherElements
|> List.filter (fun e -> e < firstElem)
|> quicksort // and sort them
let largerElements = // extract the large ones
otherElements
|> List.filter (fun e -> e >= firstElem)
|> quicksort // and sort them
// Combine the 3 parts into a new list and return it
List.concat [smallerElements; [firstElem]; largerElements]
//test
printfn "%A" (quicksort [1;5;23;18;9;1;3])C# 中的函数式实现
Correctness 正确性
Postscript 后记
Last updated