函数只对正数有效有时可以使用负数,但大多数情况下显示此错误“值-1不是UNSIGNED-BYTE类型”。
(defun OrdRapido (lista inf sup)
(let ((pivote (nth sup lista)) (i (1- inf)) (j sup) (aux))
(unless (>= inf sup)
(loop (when (>= i j) (return))
(loop (setf i (1+ i)) (when (>= (nth i lista) pivote) (return)))
(loop (setf j (1- j)) (when (<= (nth j lista) pivote) (return)))
(when (< i j)
(setf aux (nth i lista))
(setf (nth i lista) (nth j lista))
(setf (nth j lista) aux)))
(setf aux (nth i lista))
(setf (nth i lista) (nth sup lista))
(setf (nth sup lista) aux)
(OrdRapido lista inf (1- i))
(OrdRapido lista (1+ i) sup))
lista))
例如:
(setq lista2 '(-5 3 7 6 2 1 -4 100 5 80 96 14 2 3 1 0 0 789 -1 3))
(OrdRapido lista2 0 (1- (length lista2)))
CL-USER>
(-5 3 7 6 2 1 -4 100 5 80 96 14 2 3 1 0 0 789 -1 3)
CL-USER>
(-5 -4 -1 0 0 1 1 2 2 3 3 3 5 6 7 14 80 96 100 789)
但不能用这个,我只加了-to 80
'(-5 3 7 6 2 1 -4 100 5 -80 96 14 2 3 1 0 0 789 -1 3)
谢谢
修正版(增加了随机轴),我知道有更好的方法,这只是教授的一个练习
(defun OrdRapido (lista inf sup)
(let ((pivote (nth (random (1+ sup)) lista)) (i inf) (j sup) (aux))
(unless (>= inf sup)
(loop (when (> i j) (return))
(loop (when (<= (nth i lista) pivote) (return)) (setf i (1+ i)))
(loop (when (>= (nth j lista) pivote) (return)) (setf j (1- j)))
(when (<= i j)
(setf aux (nth i lista))
(setf (nth i lista) (nth j lista))
(setf (nth j lista) aux)
(setf i (1+ i))
(setf j (1- j))))
(OrdRapido lista inf j)
(OrdRapido lista i sup))
lista))
最佳答案
您试图返回列表的-1元素,但该元素不起作用。n返回列表的第n个元素,因此(nth 0'(1 2 3))将返回1但在代码中的某个时刻,它调用(nth-1(-5-80-4-10…)和boom!
关于代码的其他注释:
将结束语)放在单独的行上不是很好的lisp风格,会使代码更难阅读Lisp代码是由列表组成的,paren并不像其他语言的大括号。
使用支持您的语言的编辑器我推荐带Slim的Vim或带slime的Emacs如果你使用含有粘液的emacsthis video may help you get started。
不要用骆驼壳在你的名字所有的符号在被拘留时都是用共同的语言升级的,所以“hellother”和“hellother”或“hellother”是完全相同的符号。
另外,请查看at the rosettacode page中的quicksort,以了解如何在通用lisp(以及许多其他语言)中进行快速排序。
;; Here is a functional version for example.
(defun quicksort (list &aux (pivot (car list)) )
(if (rest list)
(concatenate 'list
(quicksort (remove-if-not #'(lambda (x) (< x pivot)) list))
(remove-if-not #'(lambda (x) (= x pivot)) list)
(quicksort (remove-if-not #'(lambda (x) (> x pivot)) list)))
list))
如果您不习惯阅读lambdas,那么这里的代码与上面的代码相同,但是lambdas被做成了本地函数,所以代码读起来更像英语。
(defun quicksort (list &aux (pivot (car list)))
(labels ((less-than-pivot (x) (< x pivot))
(greater-than-pivot (x) (> x pivot))
(equal-to-pivot (x) (= x pivot)))
(if (rest list)
(concatenate 'list
(quicksort (remove-if-not #'less-than-pivot list))
(remove-if-not #'equal-to-pivot list)
(quicksort (remove-if-not #'greater-than-pivot list)))
list)))
第二个版本在我的脑海里有点不整洁在这两个示例中,您都可以看到递归方法如何让您考虑如何只执行一步,然后通过调用自身来应用一步的解决方案,从而获得整个问题的解决方案
关于types - 我的Quicksort不适用于负数(通用Lisp),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18528957/