I have justt created my insertion sort which works fine, but I don’t understand how the recursion works.
How can 1 end up being the first element?
This is how I see the algortihm:
[5;2;17;16;1]
[2;5;17;17;1]
It stops there since 5 < 17?
let insert elem l1 =
match l1 with
[] -> [elem]
|x::l ->
if x < elem
then x::insert elem l
else elem::x::l;;
let rec sort l2 =
match l2 with
[] -> []
|h::t -> insert h (sort t);;
sort[5;2;17;16;1];
You seem to be missing a rec annotation on your insert function, which means the call at line 6 probably uses another already defined insert function if your example compiles correctly.
Once insert is properly declare as recursive, your code seems correct on your example, ^^