Upload New File
This commit is contained in:
parent
73962c4aee
commit
36cec89874
1 changed files with 47 additions and 0 deletions
47
merge-sort.rkt
Normal file
47
merge-sort.rkt
Normal file
|
|
@ -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)))]
|
||||
))
|
||||
Loading…
Add table
Add a link
Reference in a new issue