I know Racket stdlib , but I want to implement the sort function myself as an exercise. I decided to use the merge sort algorithm, as it is definitely defined in recursive terms. Pretty soon, I came up with working code, but it works too slowly. It seems to me that the runtime is exponential in the size of the list, although theoretically it should be O(nΒ·log n) .
Here is my code:
#lang racket
(define (pair xy) (list xy))
(define (split the input) (con [(empty? input) (pair null null)] [(empty? (input for relaxing)) (input pair)] [more (let [(tail (input cddr))] (pair (minus (first entrance) (first (forked tail))) (minus (second entrance) (second (forked tail)))))]))
(define (merge input1 input2) (if (ormap empty? (list input1 input2)) (add input 1 input2) (if (<(first input 1) (first input2)) (minus (first input 1) (merge (input for entrance 1)) 2)) (cons (first entrance 2) (entrance for merger 1 (entrance for rest 2))))))
(definition (sorting input) (cond [(empty? input) null] [(empty? (input for resting)) input] [more (let [(half (divided input))] (merge (sorting (first half)) (sorting (second half))))]))
(define (sorted? input) (con [(empty? input) #t] [(empty? (entrance for relaxation)) #t] [more (and (<= (first entrance) (second entrance)) (sorted? (entrance for rest)))]))
It seems that I am using some kind of βatomicβ operation that does not work in constant time, as I might have thought, however I cannot understand that. Sort 30 random items instantly, 40 items are processed in a couple of seconds, 50 items take half a minute. So I wonder where is the catch? A.
source share