scheme 快速排序
示例
Quicksort是一种常见的排序算法,平均情况复杂度为O(nlogn),最坏情况复杂度为O(n^2)。与其他O(nlogn)方法相比,它的优势在于它可以就地执行。
Quicksort将输入拆分为选定的枢轴值,将列表分为小于值和大于(或等于)枢轴的值。使用即可轻松拆分列表filter。
使用此方法,Quicksort的Scheme实现可能如下所示:
(define (quicksort lst)
(cond
((or (null? lst) ; empty list is sorted
(null? (cdr lst))) ; single-element list is sorted
lst)
(else
(let ((pivot (car lst)) ; Select the first element as the pivot
(rest (cdr lst)))
(append
(quicksort ; Recursively sort the list of smaller values
(filter (lambda (x) (< x pivot)) rest)) ; Select the smaller values
(list pivot) ; Add the pivot in the middle
(quicksort ; Recursively sort the list of larger values
(filter (lambda (x) (>= x pivot)) rest))))))) ; Select the larger and equal values
热门推荐
10 家长不续费祝福语简短
11 祝福语简短唯美10字
12 祝女儿出嫁简短祝福语
13 生日祝福语简短独特格式
14 男友红包祝福语简短精辟
15 同学表白的祝福语简短
16 对学姐的简短祝福语
17 虎年夸张祝福语大全简短
18 英语寄语生日祝福语简短