anon : write merge sort in scheme
ChatGPT :
Certainly! Here's an implementation of the merge sort algorithm in Scheme:
(define (merge-sort lst)
(if (<= (length lst) 1)
lst
(let* ((mid (quotient (length lst) 2))
(left (take lst mid))
(right (drop lst mid)))
(merge (merge-sort left) (merge-sort right)))))
(define (merge left right)
(cond ((null? left) right)
((null? right) left)
((< (car left) (car right)) (cons (car left) (merge (cdr left) right)))
(else (cons (car right) (merge left (cdr right))))))
(define (take lst n)
(if (= n 0)
'()
(cons (car lst) (take (cdr lst) (- n 1)))))
(define (drop lst n)
(if (= n 0)
lst
(drop (cdr lst) (- n 1))))
;; Example usage:
(define my-list '(5 1 4 2 8 7 3))
(display "Original List: ")
(display my-list)
(newline)
(display "Sorted List: ")
(display (merge-sort my-list))
(newline)
This code defines the merge-sort
function, which takes a list as input and sorts it using the merge sort algorithm. It also defines the helper functions merge
, take
, and drop
to facilitate the sorting process.
Make sure to load this code into your Scheme interpreter or compiler to use it. You can replace my-list
with your own list of numbers that you want to sort.