OCaml習作: マージソート

できた。

arrayでデータを受け取ってlistで返すという謎仕様なのは、データの列を分割するのはarrayのほうが簡単で、分割してソートした結果を組み立てていくのはlistのほうが簡単だったから。

open Array
open List

let rec mysort comp arr =
  match arr with
      [||] -> []
    | [|x|] -> [x]
    | [|x; y|] -> if (comp x y) then [x; y] else [y; x]
    | arr -> 
	let len = Array.length arr in
	let head = mysort comp (sub arr 0 (len / 2)) in
	let tail = mysort comp (sub arr (len / 2) (len - (len / 2))) in
	let rec merge_result ret ls1 ls2 =
	  match ls1, ls2 with
	      [], ls2 -> append (rev ret) ls2
	    | ls1, [] -> append (rev ret) ls1
	    | e1 :: es1, e2 :: es2 ->
		if (comp e1 e2) then
		  merge_result (e1 :: ret) es1 ls2
		else
		  merge_result (e2 :: ret) ls1 es2
	in
	  merge_result [] head tail;;
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy