用Scheme中的Append函数实现数字排序

时间:2016-09-24 02:28:47

标签: sorting scheme

我一直坚持实施此功能已经有一段时间了,而且无法找到合适的资源来帮助我进一步帮助。

我正在尝试实现一种数字排序,它按升序对列表中的值进行排序。

我目前的实施是:

ffmpeg -i "orig.wav" -f wav -bitexact -acodec pcm_s16le -ar 22050 -ac 1 "ffmpeg.wav"

我一直非常粗暴地计划和理解事情是如何完成的。

我的"追加" function是我在此之前实现的一个函数,它似乎按预期工作:

(define num-sort
 (lambda (ls)
    (if(null? (cdr ls))
        ls
     (if(< (car ls) (cadr ls))
        (append (car ls) (num-sort(cdr ls)))
     (if(> (car ls) (cadr ls))
        (append (num-sort(cdr ls)) (car ls))
      (num-sort(cdr ls))
      )))))

我知道递归有一个问题,在这里,当我比较两个元素并决定做另一个递归调用时,它完全搞砸了订单 - 但是我不知道如何解决这个问题

在我的脑海中,我想要做的是通过将每个元素与相邻元素进行比较来组装列表。通常情况下,我尝试通过存储和访问另一种语言的数组/变量的索引来做到这一点,但我无法理解如何在这个中正确排序。

1 个答案:

答案 0 :(得分:0)

如果你想实施选择排序,这是一个开始:

(define (num-sort ls)
  (if (null? ls)
      ls
      (num-sort-helper (car ls) '() (cdr ls))))


(define (num-sort-helper min-so-far checked unchecked)
    # min-so-far is no bigger than anything in checked
    # nothing in unchecked has been looked at

    # return a list made up of min-so-far and the elements of 
    # checked and unchecked such that that first element returned 
    # is no bigger than anything else in that list

    # For example, (num-sort-helper 5 '(6 9 7) '(8 2 3)) returns 
    # a list of all 7 numbers with 2 at the beginning

  (cond ((null? unchecked) ???)               # nothing is bigger than min-so-far
        ((<= min-so-far (car unchecked)) ???) # min-so-far is still the "winner"
        (else ???)))                          # (car unchecked) is now the "winner"