0

I'm writing a merge sort in Scheme. I have a merge sort definition, a splitter which splits the list, and a merge which merges the list.

(define mymergesort
  (lambda (alist)
    (if (null? (cdr alist)) alist
        (let ((splits (splitter alist)))
          (merge (mymergesort (car splits)) (mymergesort (cadr splits)))))))

(define splitter
  (λ (alist) (splitter-helper alist () ())))

(define splitter-helper
  (λ (alist list_a list_b)
    (cond ((null? alist) (cons (reverse list_a) (cons list_b ())))
          ((null? (cdr alist)) (cons (reverse (cons (car alist) list_a)) (cons list_b ())))
           (else (splitter-helper (reverse (cdr (reverse (cdr alist)))) (cons (car alist) list_a) (cons (car (reverse (cdr alist))) list_b))))))

(define merge
  (λ (list_a list_b)
    (cond ((null? list_a) list_b)
          ((null? list_b) list_a)
          ((<= (car list_a) (car list_b)) (cons (car list_a) (merge (cdr list_a) list_b)))
          ((<= (car list_b) (car list_a)) (cons (car list_b) (merge list_a (cdr list_b)))))))

This implementation seems to work just fine for sorting a list of numbers. But I want to be able to sort a list of mixed elements.

For example: '(I can "go" 4 "about" 123 sodas k?)

Any suggestions/solutions? I'm also trying to avoid the use of most procedures like length that "cheat" around recursive solutions.

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
kud0h
  • 35
  • 6

1 Answers1

1

You would need a 'heuristic' that ranks those items. For instance, does "go" come before "about"? What about 4? So you could write a function to determine if one element you want to sort is '<=' to another element. Also,

(<= (car list_a) (car list_b)) and then (<= (car list_b) (car list_a)) is kind of redundant. If a is not <= b, then we know a > b.

Nick Russell
  • 743
  • 1
  • 6
  • 12
  • Thanks! At first I thought your reply was really simplistic, but I sat down and really went through it, implementing my own less-than procedure. And it works perfectly! :) 6:48AM, though. – kud0h Feb 08 '13 at 13:49