Advertisement
z66is

scheme language bottom up mergesort code

Jul 5th, 2025
374
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scheme 1.26 KB | Source Code | 0 0
  1. ;; Merge two sorted lists using the given comparator
  2. (define (merge comparator list1 list2)
  3.   (define (merge01 l1 l2 acc)
  4.     (cond
  5.       ((null? l2) (append (reverse acc) l1))
  6.       ((null? l1) (append (reverse acc) l2))
  7.       ((comparator (car l2) (car l1))
  8.        (merge01 l1 (cdr l2) (cons (car l2) acc)))
  9.       (else
  10.        (merge01 (cdr l1) l2 (cons (car l1) acc)))))
  11.   (merge01 list1 list2 '()))
  12.  
  13. ;; Prepare each element as a singleton list
  14. (define (sort01 jumble)
  15.   (map list jumble))
  16.  
  17. ;; Perform one pass of merging adjacent pairs
  18. (define (sort02 comparator lists)
  19.   (cond
  20.     ((null? lists) '())
  21.     ((null? (cdr lists)) lists)
  22.     (else
  23.      (cons (merge comparator (car lists) (cadr lists))
  24.            (sort02 comparator (cddr lists))))))
  25.  
  26. ;; Repeatedly merge until one list remains
  27. (define (sort03 comparator lists)
  28.   (cond
  29.     ((null? lists) '())
  30.     ((null? (cdr lists)) (car lists))
  31.     (else
  32.      (sort03 comparator (sort02 comparator lists)))))
  33.  
  34. ;; Top‐level sort: prepare, merge‐pass, then finalize
  35. (define (sort comparator jumble)
  36.   (sort03 comparator (sort02 comparator (sort01 jumble))))
  37.  
  38. ;; Entry point: sort the sample list in descending order then display
  39. (define (main)
  40.   (display (sort > '(4 3 5 6 8 7 1 2 9)))
  41.   (newline))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement