【问题标题】:Insertion sort in Racket, cannot figure out why this doesn't work球拍中的插入排序,无法弄清楚为什么这不起作用
【发布时间】:2016-11-16 00:33:47
【问题描述】:

我是 Racket 的新手,我正在尝试找出插入排序。这就是我所拥有的,但我遇到了一个错误,我无法从调试中弄清楚。

;Definition of insert: inserts a number into an already sorted list based on
;the cmp parameter
;cmp: < or >, L1: a list, n: the number to be inserted
(define (insert cmp L1 n)
  (cond
    ((null? n) (list L1))
    ((null? L1) (cons n L1))
    ((cmp n (car L1)) (cons n L1))
    (else (cons (car L1) (insert cmp (cdr L1) n)))
   )
)

;Definition of insertionSort: sorts a list based on a recursive insertion sort
;L1: a list, cmp: < or >
(define (insertionSort L1 cmp)
  (cond
    ((null? L1) L1)
    (else (insert cmp (car L1) (insertionSort(cdr L1) cmp)))
  )
)

【问题讨论】:

  • (null? n) 中的insert 不是很有用,因为n 是一个数字。

标签: recursion scheme racket insertion-sort


【解决方案1】:

以下功能起作用:

(define (insert n l cmp (ol '()))
  (cond
    [(empty? l)
     (append ol (list n))] ; or: (reverse (cons n (reverse ol)))
    [(not (cmp n (first l)))
     (append ol (list n) l)]
    [else (insert n
                  (rest l)
                  cmp
                  (append ol (list (first l))) ; or:  (reverse (cons (first l) (reverse ol)))
                  )] ))

(define (isort l cmp (sl '()))
  (cond
    [(empty? l) sl]
    [else (isort (rest l)
                 cmp
                 (insert (first l)
                         sl
                         cmp))] ))

这些函数似乎是尾递归的。

测试:

(isort '(4 2 5 8 1 4 7 3 6 9) >)
(isort '(4 2 5 8 1 4 7 3 6 9) <)

输出:

'(1 2 3 4 4 5 6 7 8 9)
'(9 8 7 6 5 4 4 3 2 1)

【讨论】:

    【解决方案2】:

    当您在insertionSort 中使用insert 时,您已经“翻转”了它的参数;应该是

    (define (insertionSort L1 cmp)
      (cond
        ((null? L1) L1)
        (else (insert cmp (insertionSort (cdr L1) cmp) (car L1)))))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      • 2012-05-16
      • 1970-01-01
      相关资源
      最近更新 更多