Skip to content

Instantly share code, notes, and snippets.

@louy2
Created February 21, 2020 03:52
Show Gist options
  • Save louy2/d3cd4c74a68ebe325268b9a64fee24ca to your computer and use it in GitHub Desktop.
Save louy2/d3cd4c74a68ebe325268b9a64fee24ca to your computer and use it in GitHub Desktop.
Merge sort demo with Racket because DrRacket debug mode shows the stack nicely
#lang racket
(define (merge-sort l)
(cond
[(null? (cdr l)) l]
[else (let-values
([(l1 l2) (split-in-half l)])
(merge (merge-sort l1) (merge-sort l2)))]))
(define (split-in-half l)
(split-at l (quotient (length l) 2)))
(define (merge l1 l2)
(cond
[(null? l1) l2]
[(null? l2) l1]
[(<= (car l1) (car l2))
(cons (car l1) (merge (cdr l1) l2))]
[(< (car l2) (car l1))
(cons (car l2) (merge l1 (cdr l2)))]))
(merge-sort '(45 3 2 5 80 38 44 92 3 6 -3 -7 9 0 4 85))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment