Skip to content

Instantly share code, notes, and snippets.

@SamuelNittala
Last active July 2, 2023 01:50
Show Gist options
  • Save SamuelNittala/a4c8fa6604eea436def8fd838d0b21fc to your computer and use it in GitHub Desktop.
Save SamuelNittala/a4c8fa6604eea436def8fd838d0b21fc to your computer and use it in GitHub Desktop.
insertion sort recursive
// inserts the element at index i into the correct position,
// [0..i-1] must be sorted
function insert_rec(l, i) {
if (i == 0) return l;
else {
if (l[i] < l[i - 1]) {
return compare_rec(
[...l.slice(0, i - 1), l[i], l[i - 1], ...l.slice(i + 1)],
i - 1
);
} else {
return compare_rec(l, i - 1);
}
}
}
function insert_sort_rec(l, i) {
if (i == l.length) return l;
return insert_sort_rec(insert_rec(l, i), i + 1);
}
console.log(insert_sort_rec([4,5,1,3], 0));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment