问题描述
假设你插入 (15) 如果我运行这个程序,输出将是 (14 16 17 18 19) 如何让程序在正确的位置 (pos = 1) 插入数字 15 或在正确的位置 (pos) 插入任何数字 (n)。
(define list1 '(14 16 17 18 19))
(define lst (list))
(define (insert lst n)
(if (empty? lst)
'()
(foldr cons (list n) lst))) ;The value gets inserted at the end of the list
解决方法
我们有很多排序算法,比如快速排序、直方图排序、冒泡排序。
您可以查看此 Sorting Algorithms 或维基百科。
如果 n
大于列表中的每个数据,lst
变成 '()
我们只返回 (list n)
例如(f '() 1) -> '(1)
当 n
小于或等于第一个元素时,我们在第一个位置插入。
例如(f '(2) 1) -> (cons 1 '(2))
如果不是我们想要这样的数据:
(f '(1 2 4) 3) -> (cons 1 (f '(2 4) 3)) -> (cons 1 (cons 2 (f '(4) 3))) -> (cons 1 (cons 2 (cons 3 '(4)))) -> (list 1 2 3 4)
(define (insert-with-<-order lst n)
(cond
[(empty? lst)
(list n)]
[(<= n (first lst))
(cons n lst)]
[else
(cons (first lst)
(insert-with-<-order (rest lst) n))]))
(insert-with-<-order '(1 1 2 3) 1.5)
(insert-with-<-order '(-2 0.5 1 2 5) 0.1)
(insert-with-<-order '(1 2 3) 4)
使用sort
(define (insert-with-order lst n)
(sort (cons n lst) <))
(insert-with-order '(14 16 17 18 19) 15)