previous | index | next

Merging Two Sorted Lists

Q: If you're merging lst1 and lst2 and either is empty, what do you return?

A: The other list

Q: If the head of lst1 is less than the head of lst2, what do you return?

A: The result of consing the head of lst1 onto the result of merging the tail of lst1 with lst2

Q: If the head of lst2 is less than the head of lst1, what do you return?

A: The result of consing the head of lst2 onto the result of merging the tail of lst2 with lst1

Q: If the head of lst1 is equal to the head of lst2, what do you do?

A: Ignore one of the duplicates

   (define merge
     (lambda (lst1 lst2)
       (cond ((null? lst1) lst2)
             ((null? lst2) lst1)
              (cons (car lst1)
                    (merge (cdr lst1) lst2)))
             ((< (car lst2) (car lst1)) 
              (cons (car lst2)
                    (merge  lst1 (cdr lst2))))
             (else 
              (cons (car lst1) 
                    (merge (cdr lst1) (cdr lst2)))))))

previous | index | next