Algorithm-FSharp/Algorithm-FSharp/QuickSort.fs

23 lines
1.4 KiB
Forth
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

module Algorithm_FSharp.QuickSort
// 序列切割算法
// partition : ('a -> bool) -> 'a list -> 'a list * 'a list
// 按pred切割序列返回的元组中第一个元素是满足条件的元素序列第二个元素是不满足条件的元素序列
let rec partition pred lst =
match lst with // 模式匹配
| [] -> [],[] // list为空返回两个空列表
| head::tail -> // list不为空切割出第一个元素head和剩余的元素组成的序列tail
let matched, unmatched = partition pred tail // 递归调用partition完成序列切割此时matched、unmatched分别为匹配谓词和不匹配谓词的元素序列
match (pred head) with // 对当前元素进行判断
| true -> head::matched, unmatched // 若匹配谓词则将其追加至matched的头部并返回
| false -> matched, head::unmatched // 若不匹配谓词将其追加至unmatched的头部并返回
// quicksort : 'a list -> 'a list
// 快速排序的F#实现
let rec quicksort i =
match i with // 模式匹配
| [] -> [] // 空列表和只有一个元素的列表都返回自身即可
| [single] -> [single] // 这两种情况下序列都完全有序
| head :: tail -> // 多于一个元素的列表,选取列表的头元素作为参考数
let leftList, rightList = partition (fun item -> item <= head) tail // 调用partition完成序列切割
quicksort(leftList) @ [head] @ quicksort(rightList) //