我试图在Common Lisp中提出快速排序的实现,这是我到目前为止所做的:
(defun quick-sort (list)
(if (cdr list)
(let ((pivot (car list)))
(append (quick-sort (remove-if-not (lambda (n) (< n pivot)) list))
(remove-if-not (lambda (n) (= n pivot)) list)
(quick-sort (remove-if-not (lambda (n) (> n pivot)) list))))
list))
显然它可行,但我认为该代码中有太多重复。基本上,我们有三次:
(remove-if-not (lambda (n) (< n pivot)) list)
这三个来电的唯一不同方式是>
vs =
vs <
。
因此我的问题是:如何删除冗余并使代码更具可读性和更紧凑?
当然,我可以将事物提取到函数中,例如:
(defun which (operator pivot list )
(remove-if-not (lambda (n) (funcall operator n pivot)) list))
(defun quick-sort (list)
(if (cdr list)
(let ((pivot (car list)))
(append (quick-sort (which #'< pivot list))
(which #'= pivot list)
(quick-sort (which #'> pivot list))))
list))
但不知何故,我并不确定这是否是最佳方法。一次又一次地移交pivot
和list
仍然感觉很笨拙。
我也有使用flet
的想法,它使函数的实际主体更具可读性,但只将复杂性移到其他地方:
(defun quick-sort (list)
(if (cdr list)
(let ((pivot (car list)))
(flet ((left () (remove-if-not (lambda (n) (< n pivot)) list))
(middle () (remove-if-not (lambda (n) (= n pivot)) list))
(right () (remove-if-not (lambda (n) (> n pivot)) list)))
(append (quick-sort (left))
(middle)
(quick-sort (right)))))
list))
还有其他方法吗?
答案 0 :(得分:16)
如果你把它写成本地函数,你就不必传递额外的参数,因为它们在范围内。
(defun quick-sort (list)
(if (rest list)
(let ((pivot (first list)))
(flet ((filter (operator)
(remove-if-not (lambda (n) (funcall operator n pivot)) list)))
(append (quick-sort (filter #'<))
(filter #'=)
(quick-sort (filter #'>)))))
list))
稍微紧凑的版本:
(defun quick-sort (list &aux (pivot (first list)))
(flet ((filter (operator)
(remove-if-not (lambda (n) (funcall operator n pivot)) list)))
(and list
(nconc (quick-sort (filter #'<))
(filter #'=)
(quick-sort (filter #'>))))))
由于Common Lisp支持多个值,您也可以一次性在一个函数中对列表进行分区,并将列表作为值返回:
(defun partition (list pivot)
(loop for e in list
when (< e pivot) collect e into smaller else
when (> e pivot) collect e into larger else
when (= e pivot) collect e into same
finally (return (values smaller same larger))))
(defun quick-sort (list)
(if (rest list)
(multiple-value-bind (smaller same larger)
(partition list (first list))
(append (quick-sort smaller) same (quick-sort larger)))
list))
当新分配列表时,NCONC
是可能的。由于REMOVE-IF-NOT
是非破坏性的(与DELETE-IF-NOT
比较),NCONC
很好。由于LOOP
收集了新列表,NCONC
再次正常。
这是一个真正简单的就地Quicksort而不是矢量。请注意,Quicksort实际上就是这种意思。使用列表的版本不是真正的Quicksort。
(defun partition (array left right &aux (i (1- left))
(j right)
(v (aref array right)))
(loop do (loop do (incf i) until (>= (aref array i) v))
(loop do (decf j) until (or (zerop j)
(<= (aref array j) v)))
(rotatef (aref array i) (aref array j))
until (<= j i))
(rotatef (aref array j) (aref array i) (aref array right))
i)
(defun quicksort (array &optional (left 0) (right (1- (length array))))
(if (> right left)
(let ((i (partition array left right)))
(quicksort array left (1- i))
(quicksort array (1+ i) right))
array))
此版本基于Sedgewick的代码。