气泡分选方案 [英] Bubble Sorting in Scheme
问题描述
我正在将递归代码编写为Bubble Sort(通过交换从最小到最大)
我有一个代码可以只对气泡进行一次排序
I am writing a recursive code to Bubble Sort (smallest to largest by swapping)
I have a code to do the bubble sort just once
(define (bubble-up L)
(if (null? (cdr L))
L
(if (< (car L) (cadr L))
(cons (car L) (bubble-up (cdr L)))
(cons (cadr L) (bubble-up (cons (car L) (cddr L))))
)
)
如果我在此代码中放入了一个列表,它将返回结尾处编号最大的列表.
EX ..(冒泡'(8 9 4 2 6 7))->'(8 4 2 6 7 9)
if i put a list into this code, it returns the list with the largest number at the end
EX.. (bubble-up ' (8 9 4 2 6 7)) -> ' (8 4 2 6 7 9)
现在我正在尝试编写代码以执行(泡沫L)N次(列表中整数的数量)
我有以下代码:
Now i am trying to write a code to do the (bubble-up L) N times (the number of integers in list)
I have this code:
(define (bubble-sort-aux N L)
(cond ((= N 1) (bubble-up L))
(else (bubble-sort-aux (- N 1) L)
(bubble-up L))))
(bubble-sort-aux 6 (list 8 9 4 2 6 7)) -> ' (8 4 2 6 7 9)
但是递归似乎没有发生,因为它只排序一次!
任何建议都将受到欢迎,我很困惑!
But the recursion doesn't seem to happen because it only sorts once!
Any suggestions would be welcome, i'm just stumped!
推荐答案
尝试一下:
(define (bubble-sort-aux N L)
(cond ((= N 1) (bubble-up L))
(else (bubble-sort-aux (- N 1) (bubble-up L)))))
如果您继续冒泡"列表N
次,它将在末尾排序.您的代码的问题在于您没有将bubble-up
的结果用于任何东西-但是,如果我们将bubble-up
返回的值传递给函数的下一个调用,则最终将对它进行排序.现在,该过程将按预期工作:
If you keep "bubbling-up" the list N
times it'll be sorted at the end. The problem with your code is that you weren't using the result of bubble-up
for anything - but if we pass the value returned by bubble-up
to the next call of the function, it'll eventually be sorted. Now the procedure works as expected:
(bubble-sort-aux 6 (list 8 9 4 2 6 7))
=> '(2 4 6 7 8 9)
这篇关于气泡分选方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!