@@ -104,9 +104,8 @@ let rec sort_rec (<=) n xs =
104104 let s2, xs2 = sort_rec (< = ) n2 xs1 in
105105 (merge (< = ) s1 s2, xs2)
106106
107- let sort (<=) = function
108- | [] -> []
109- | xs -> fst (sort_rec (< = ) (length xs) xs)
107+ let sort (<=) xs =
108+ if xs = [] then [] else fst (sort_rec (< = ) (length xs) xs)
110109
111110end ;;
112111
@@ -131,6 +130,66 @@ let sort (<=) s = sort_rec (<=) 0 [] s
131130
132131end ;;
133132
133+ module Smooth = struct
134+
135+ open NTRMerge
136+
137+ let rec push (<=) xs k stack =
138+ match k mod 2 , stack with
139+ | 0 , _ -> xs :: stack
140+ | 1 , ys :: stack -> push (< = ) (merge (< = ) ys xs) (k / 2 ) stack
141+
142+ let rec pop (<=) xs = function
143+ | [] -> xs
144+ | ys :: stack -> pop (< = ) (merge (< = ) ys xs) stack
145+
146+ let rec sort_rec (<=) k stack s =
147+ let rec sort_rec ' mode accu x s =
148+ let accu = x :: accu in
149+ match s with
150+ | y :: s when (x < = y) = mode -> sort_rec' mode accu y s
151+ | _ -> sort_rec (< = ) (k + 1 )
152+ (push (< = ) (if mode then rev accu else accu) k stack) s
153+ in
154+ match s with
155+ | x :: y :: s -> sort_rec' (x < = y) [x] y s
156+ | _ -> pop (< = ) s stack
157+
158+ let sort (<=) s = sort_rec (< = ) 0 [] s
159+
160+ end ;;
161+
162+ module TailRec = struct
163+
164+ open TRMerge
165+
166+ let rec push (<=) mode xs k stack =
167+ let (>=) x y = (< = ) y x in
168+ match k mod 2 , stack with
169+ | 0 , _ -> xs :: stack
170+ | 1 , ys :: stack ->
171+ push (< = ) (not mode)
172+ (if mode then rev_merge (> = ) xs ys [] else rev_merge (< = ) ys xs [] )
173+ (k / 2 ) stack
174+
175+ let rec pop (<=) mode xs k stack =
176+ match k mod 2 , stack with
177+ | _ , [] -> if mode then rev xs else xs
178+ | 0 , _ -> pop (< = ) (not mode) (rev xs) (k / 2 ) stack
179+ | 1 , ys :: stack ->
180+ pop (< = ) (not mode)
181+ (if mode then rev_merge (> = ) xs ys [] else rev_merge (< = ) ys xs [] )
182+ (k / 2 ) stack
183+
184+ let rec sort_rec (<=) k stack =
185+ function
186+ | x :: s -> sort_rec (< = ) (k + 1 ) (push (< = ) false [x] k stack) s
187+ | [] -> pop (< = ) false [] k stack
188+
189+ let sort (<=) s = sort_rec (< = ) 0 [] s
190+
191+ end ;;
192+
134193(* Stack-based bottom-up non-tail-recursive mergesorts *)
135194module NTRStack = struct
136195
0 commit comments