I am implementing merge sort in scheme, and I must do it by defining two helper methods: merge and split.
Merge takes two lists (already in increasing order) and merges them together. I have done this as follows:
(define merge
(lambda (list1 list2)
(if (null? list1)
list2
(if (null? list2)
list1
(if (< (car list1) (car list2))
(cons (car list1) (merge (cdr list1) list2))
(cons (car list2) (merge (cdr list2) list1)))))))
The split method has me stumped though. I’ve found an example that accomplishes this in two separate methods (‘odd-numbers’ and ‘even-numbers’), but I was wondering if there was a way to combine these into one method called ‘split’?
Example found here: merge sort in scheme
I am obviously quite new to scheme, can anyone help me understand how to do this?
A simplistic
splitimplementation, suitable for use as part of amergesort, follows:It splits the input list in two halves, returning them in a list of lists – the first list corresponds to the first half, and the second list corresponds to the second half of the input list.
Another alternative, as requested in the question, would be to split the list in odd/even elements like this:
Yet another alternative, by using
partitionyou can split the input list in a single pass:Be aware that the last two alternatives will be useful only if the input list contains exclusively integer numbers, for sorting lists of other data types with your own implementation of
mergesort, you’re better off using my first version ofsplit.