这是我实现快速排序的尝试:
(define (sublist ls start stop middle)
(cond ( (null? ls) ls)
( (< middle start) (sublist (cdr ls) start stop (+ middle 1)))
( (> middle stop) '() )
(else
(cons (car ls) (sublist (cdr ls) start stop (+ middle 1))))))
(define (split5 ls)
(let ((len (length ls)))
(cond ((= len 0) (list ls ls) )
((= len 1) (list ls '() ))
(else
(list (sublist ls 1 (/ len 2) 1)
(sublist ls (+(/ len 2)1) len 1))))))
;this divides the sorted list into two sublists
(define (dividelist rel? ls)
(split5 (order rel? ls)))
(define (quicksort rel? ls)
(if (null? (cdr ls)) ls
(let ((pivot (list-ref (sort rel? ls) (round (/ (length (sort rel? ls)) 2))))
(left (car (dividelist rel? ls)))
(right (cdr (dividelist rel? ls))))
(join left pivot right))))
我知道这种实现效率很低,但我想不出办法。无论如何,它真的不起作用。
When I input this:
(quicksort < '(9 3 -5 8 -7 2 9))
It gives me this:
(-7 -5 2 8 (8 9 9))
It should give me this:
(-7 -5 2 3 8 9 9)
我怎样才能解决这个问题?
编辑
(define (join ls1 goo ls2)
(if (null? ls1) (cons goo ls2)
(if (null? ls2) (cons goo ls1)
(cons (car ls1) (join (cdr ls1) goo ls2)))))