Skip to content

Commit bb350d1

Browse files
authored
Merge pull request #1 from MatrixWood/dev
update merge sort
2 parents e823b97 + d23bbc1 commit bb350d1

1 file changed

Lines changed: 37 additions & 6 deletions

File tree

algorithm.ml

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,21 @@
1-
(* factorial : int -> int *)
1+
(*
2+
val factorial : int -> int = <fun>
3+
val length : 'a list -> int = <fun>
4+
val take : int -> 'a list -> 'a list = <fun>
5+
val drop : int -> 'a list -> 'a list = <fun>
6+
val sort_insert : 'a -> 'a list -> 'a list = <fun>
7+
val sort : 'a list -> 'a list = <fun>
8+
val merge : ('a -> 'a -> bool) -> 'a list -> 'a list -> 'a list = <fun>
9+
val split : 'a list -> 'a list -> 'a list -> 'a list * 'a list = <fun>
10+
val mergesort : ('a -> 'a -> bool) -> 'a list -> 'a list = <fun>
11+
val map : ('a -> 'b) -> 'a list -> 'b list = <fun>
12+
13+
*)
214
let rec factorial a =
315
match a with
416
| 1 -> 1
517
| _ -> a * factorial (a - 1)
618

7-
(* isvowel : int -> int *)
8-
let rec isvowel c =
9-
c = 'a' || c = 'e' || c = 'i' || c = 'o' || c = 'u'
10-
11-
1219
let rec length l =
1320
match l with
1421
| [] -> 0
@@ -41,3 +48,27 @@ let rec sort l =
4148
| [] -> []
4249
| h :: t -> sort_insert h (sort t)
4350

51+
let rec merge cmp x y =
52+
match (x, y) with
53+
| ([], _) -> y
54+
| (_, []) -> x
55+
| (h1 :: t1, h2 :: t2) ->
56+
if cmp h2 h1
57+
then h1 :: (merge cmp t1 y)
58+
else h2 :: (merge cmp x t2)
59+
60+
and split x y z =
61+
match x with
62+
| [] -> (y, z)
63+
| x :: resto -> split resto z (x :: y)
64+
65+
and mergesort cmp x =
66+
match x with
67+
| ([] | _ :: []) -> x
68+
| _ -> let (pri, seg) = split x [] []
69+
in (merge cmp (mergesort cmp pri) (mergesort cmp seg))
70+
71+
let rec map f l =
72+
match l with
73+
| [] -> []
74+
| h::t -> f h :: map f t

0 commit comments

Comments
 (0)