Skip to content

Instantly share code, notes, and snippets.

@fortunee
Last active March 9, 2023 04:17
Show Gist options
  • Save fortunee/dc2e7a7f8378badeb73a17d4381f9923 to your computer and use it in GitHub Desktop.
Save fortunee/dc2e7a7f8378badeb73a17d4381f9923 to your computer and use it in GitHub Desktop.
Insertion Sort: sorting algorithm
/**
* Insertion sort:
* Big O notation of O(n^2) due to the double loop
*/
const insertionSort = (items) => {
/**
* 1. Loop through array of unsorted items
* 2. Grab the value of the current iteration index
* 3. Initialize j index for a second loop back through the sorted section
* 4. Loop back and compare the last item in the sorted section with the
* current item in iteration of the first loop
* 5. When each item in the sorted section from the last item > current item in
* iteration of the first loop we insert into position of the current item in
* iteration of the second loop
* 6. We set as the final value for when there's no item in the sorted section
* > current item in iteration of the first loop
*/
for (let i = 0; i < items.length; i++) {
let value = items[i];
let j = 0;
for (j = i - 1; j > -1 && items[j] > value; j--) {
items[j + 1] = items[j];
}
items[j+1] = value;
}
return items;
}
const unsortedList = [2,10,23,13,23,5,1,6,8,9,3,7,4,3,7,9,30,15,21,22,17,4,5];
const sortedList = insertionSort(unsortedList);
console.log(sortedList) // [ 1, 2, 3, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9, 9, 10, 13, 15, 17, 21, 22, 23, 23, 30 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment