首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QuickSort方案

QuickSort方案
EN

Stack Overflow用户
提问于 2013-10-31 18:44:25
回答 1查看 1.7K关注 0票数 0

我需要实现以下快速排序:(quick-sort pred lst) lst是要排序的数字列表pred是该列表的排序依据,此谓词的签名为:(lambda (x,y)…)

这里的代码是有效的,但这里的问题是,当我进入相同的数字时,当我进入无限循环时,经过几个小时的调试,我找不到问题或如何解决它。

代码语言:javascript
复制
(define (quick-sort pred lst)

;Pivot is 1st element of the list
 (define (pivot lst)
  (if (or (null? lst) (= 1 (length lst)))
    'done
     (car lst)))

 partition get the pivot the list and the predicate and splitting it to two lists
  (define (partition piv lst pred)

    ;predPos is the pred it slef and predNeg is the negative of the pred
     (let* ((predPos (lambda (x) (pred x piv) )) 
            (predNeg (lambda (x) (if (pred x piv) #f #t)))

            ;Filtering the big list in to two lists
            (p1 (filter predPos lst))
            (p2 (filter predNeg lst)))

          ;Recursivly doing the qucicksort on each list. and joining them together.
           (cond ((and (null? p1) (null? p2)) (cons piv ()))
                 ((null? p1) (quick-sort pred p2))
                 ((null? p2) (quick-sort pred p1))
                 (else (joiner (quick-sort pred p1) (quick-sort pred p2))))))


      ;Joining 2 lists together
      (define (joiner p1 p2)
      (cond ((null? p1) p2)
            ((null? p2) p1)
            (else (cons  (car p1) (joiner (cdr p1) p2)))))

 ;The main quicksort method () and list size one are sorted!
 (let ((piv (pivot lst)))
   (if (or (null? lst) (= 1 (length lst)))
      lst
      (partition piv lst pred))))
EN

回答 1

Stack Overflow用户

发布于 2013-10-31 19:03:36

如果您在分区之前删除了pivot,则可以保证在每个递归步骤中都会取得进展。如果没有这一措施,轴心将停留在其分区的前面,您将无法到达任何位置。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19704348

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档