问题
I created a function (mergesort) in ocaml but when I use it, the list is inverted.
In addition, I want to calculate the time the system takes to do the calculation, how can I do it?
let rec merge l x y = match (x,y) with
| ([],_) -> y
| (_,[]) -> x
| (h1::t1, h2::t2) ->
if l h1 h2
then h1::(merge l t1 y)
else h2::(merge l x t2);;
let rec split x y z = match x with
| [] -> (y,z)
| x::resto -> split resto z (x::y);;
let rec mergesort l x = match x with
| ([] | _::[]) -> x
| _ -> let (pri,seg) = split x [] []
in merge l (mergesort l pri) (mergesort l seg);;
mergesort (>) [2;6;1;8];;
- : int list = [8; 6; 2; 1]
回答1:
Change the line if l h1 h2
by if l h2 h1
. The way of comparing the head elements from the two sublists gives you a inverted list.
Also, I can propose you to use the following syntax when you have multiples recursives functions calling each other :
let rec merge cmp x y = match (x,y) with
| ([],_) -> y
| (_,[]) -> x
| (h1::t1, h2::t2) ->
if cmp h2 h1
then h1::(merge cmp t1 y)
else h2::(merge cmp x t2)
and split x y z = match x with
| [] -> (y,z)
| x::resto -> split resto z (x::y)
and mergesort cmp x = match x with
| ([] | _::[]) -> x
| _ -> let (pri,seg) = split x [] []
in (merge cmp (mergesort cmp pri) (mergesort cmp seg));;
To measure the time function, you can have a look here : Running time in Ocaml
回答2:
For benchmark a function see Core_Bench https://blogs.janestreet.com/core_bench-micro-benchmarking-for-ocaml/.
来源:https://stackoverflow.com/questions/33566414/ocaml-mergesort-and-time