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]
Change the line
if l h1 h2
byif 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 :
To measure the time function, you can have a look here : Running time in Ocaml
For benchmark a function see Core_Bench https://blogs.janestreet.com/core_bench-micro-benchmarking-for-ocaml/.