sicp每日一题[2.61]

Exercise 2.61

Give an implementation of adjoin-set using the ordered representation. By analogy with element-of-set? show how to take advantage of the ordering to produce a procedure that requires
on the average about half as many steps as with the unordered representation.


这道题实现起来倒是不难,每次比较一下集合第一个元素和要插入的元素的大小,如果要插入的数小于等于集合第一个元素,就直接用 cons 把这个新元素和集合连接起来; 如果要插入的元素大于集合第一个元素,
就把集合第一个元素和要插入元素和集合其他项连接的结果连接起来就行了。最差的情况就是,要插入的元素比集合最大的元素还要大,这样要遍历整个集合,此时和原来的实现没有区别; 在其他情况,平均应该可以节省一半的步骤。

(define (adjoin-set x set)
  (let ((first (car set)))
    (cond ((null? set) (list x))
          ((<= x first) (cons x set))
          (else (cons first (adjoin-set x (cdr set)))))))
      

(define set1 (list 1 3 5 7 9))
(adjoin-set 6 set1)

; 执行结果 
'(1 3 5 6 7 9)
posted @ 2024-10-29 08:17  再思即可  阅读(6)  评论(0编辑  收藏  举报