Created
May 23, 2022 21:02
-
-
Save jayantasamaddar/b439da0576de6ceed14678cf3b45391e to your computer and use it in GitHub Desktop.
Implement an Insertion Sort Algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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