diff --git a/merge-sort.rkt b/merge-sort.rkt new file mode 100644 index 0000000..6b1f0a1 --- /dev/null +++ b/merge-sort.rkt @@ -0,0 +1,47 @@ +;; The first three lines of this file were inserted by DrRacket. They record metadata +;; about the language level of this file in a form that our tools can easily process. +#reader(lib "htdp-advanced-reader.ss" "lang")((modname merge-sort) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #t #t none #f () #f))) +(define (merge lst1 lst2) (cond + [(empty? lst1) lst2] + [(empty? lst2) lst1] + [(<= (first lst1) (first lst2)) (cons (first lst1) (merge (rest lst1) lst2))] + [else (cons (first lst2) (merge lst1 (rest lst2)))] + )) + +(define (is-sorted? lst) (cond + [(empty? lst) true] + [(empty? (rest lst)) true] + [(> (first lst) (second lst)) #f] + [else (is-sorted? (rest lst))] + )) + +(define (take lst n) (cond + [(empty? lst) empty] + [(= n 0) empty] + [(= n 1) (list (first lst))] + [else (cons (first lst) (take (rest lst) (- n 1)))] + )) + +(define (skip lst n) (cond + [(empty? lst) empty] + [(= n 0) lst] + [else (skip (rest lst) (- n 1))] + )) + +(define (upper-half lst) (cond + [(empty? lst) empty] + [else (take lst (floor (/ (length lst) 2)))] + )) + + + +(define (lower-half lst) (cond + [(empty? lst) empty] + [else (skip lst (floor (/ (length lst) 2)))] + )) + +(define (merge-sort lst) (cond + [(empty? lst) lst] + [(empty? (rest lst)) lst] + [else (merge (merge-sort (upper-half lst)) (merge-sort (lower-half lst)))] + )) \ No newline at end of file