I have a Racket homework problem that asks me to create a mergesort function using recursion. It is supposed to take a list, split it up into smaller lists, and then sort them from least to greatest. The function is also supposed to return that sorted list without using any sorting commands in this assignment.
This is the code I have so far:
(define (mergesort lst)
(cond
[(empty? lst) '()]
[(= (length lst) 1) lst]
[(let* ([index 0][end_index (- (length lst) 1)])
(if (< (list-ref lst index) (list-ref lst (add1 index)))
(cons...)
(cons...)
))]
)
)
(mergesort '(3 1 2 7 9)) ;should return (1 2 3 7 9)
I am struggling with figuring out how to move the elements into their proper position (from least to greatest) when the if statement is met. Am I on the right track?
To split a list into two sublists, you can use functions
takeanddrop. For example:Given two sorted lists, the following function returns a sorted list containing all elements from both lists:
For example:
Thus, the merge-sort algorithm can be coded as follows:
Example: