I am new to Scheme and I am using Dr.Racket to try to find the median of the list.
If the length of list L is odd, the function median returns the median element in the
This problem can be solved using the tortoise and hare algorithm, provided that a helper inner procedure is allowed - we need to pass two parameters for this to work. Other than that, all the restrictions are enforced:
(define (median lst)
(define (median tortoise hare)
(cond ((null? hare) 0)
((null? (cdr hare)) (car tortoise))
(else (median (cdr tortoise) (cdr (cdr hare))))))
(median lst lst))
It works as expected:
(median '(1)) ; returns 1
(median '(1 2)) ; returns 0
(median '(1 2 3)) ; returns 2
(median '(1 2 3 4)) ; returns 0