Skip to content

Commit 520665b

Browse files
committed
Add a recursive implementation of Insertion Sort
1 parent 335258f commit 520665b

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

src/Index.re

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,7 @@ Invariant.expect(Array.of_list(expected_list) == sorted_array);
1313

1414
let sorted_list_2 = SelectionSort.sort(unsorted_list);
1515

16-
Invariant.expect(sorted_list_2 == expected_list);
16+
Invariant.expect(sorted_list_2 == expected_list);
17+
18+
let sorted_list_3 = RecursiveInsertionSort.sort(unsorted_list);
19+
Invariant.expect(sorted_list_3 == expected_list);

src/RecursiveInsertionSort.re

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
let rec insert_item = (items: list(int), item: int) =>
2+
switch (items) {
3+
| [] => [item]
4+
| [head, ...rest] when item < head => [item, head, ...rest]
5+
| [head, ...rest] when item > head =>
6+
let sorted_rest = insert_item(rest, item);
7+
[head, ...sorted_rest];
8+
};
9+
10+
let rec sort = items : list(int) =>
11+
switch (items) {
12+
| [] => []
13+
| [head, ...rest] => insert_item(sort(rest), head)
14+
};

0 commit comments

Comments
 (0)