Skip to content

Instantly share code, notes, and snippets.

@jayantasamaddar
Created May 23, 2022 21:02
Show Gist options
  • Save jayantasamaddar/b439da0576de6ceed14678cf3b45391e to your computer and use it in GitHub Desktop.
Save jayantasamaddar/b439da0576de6ceed14678cf3b45391e to your computer and use it in GitHub Desktop.
Implement an Insertion Sort Algorithm
/* Using C-Style for-loop */
const insertionSort = array => {
const arr = array.slice();
for (let i = 1; i < arr.length; i++) {
const sortedArr = arr.slice(0, i);
for (let j = 0; j < sortedArr.length; j++) {
if (sortedArr[j] > arr[i]) {
const pickedEl = arr.splice(i, 1)[0];
arr.splice(j, 0, pickedEl);
break;
}
}
}
return arr;
};
/* Using while loop */
const insertionSort2 = array => {
const arr = array.slice();
let i = 1;
while (i < arr.length) {
const sortedArr = arr.slice(0, i);
let j = 0;
while (j < sortedArr.length) {
if (sortedArr[j] > arr[i]) {
const pickedEl = arr.splice(i, 1)[0];
arr.splice(j, 0, pickedEl);
break;
}
j++;
}
i++;
}
return arr;
};
/* Using Recursive Function */
const insertionSort3 = array => {
const recursiveSort = (arr, i) => {
if (i === arr.length) return arr;
const sortedArr = arr.slice(0, i);
for (let j = 0; j < sortedArr.length; j++) {
if (sortedArr[j] > arr[i]) {
const pickedEl = arr.splice(i, 1)[0];
arr.splice(j, 0, pickedEl);
break;
}
}
return recursiveSort(arr, i + 1);
};
return recursiveSort([...array], 0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment