Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@CharmedSatyr
Last active August 1, 2018 04:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CharmedSatyr/1a3bc1b88f0a21857900714d39c2199a to your computer and use it in GitHub Desktop.
Save CharmedSatyr/1a3bc1b88f0a21857900714d39c2199a to your computer and use it in GitHub Desktop.
Insertion Sort implemented in JavaScript
/* This method works by building up a sorted array at the beginning of
* the list. It begins the sorted array with the first element. Then it
* inspects the next element and swaps it backwards into the sorted
* array until it is in sorted position. It continues iterating through
* the list and swapping new items backwards into the sorted portion
* until it reaches the end.
*/
'use strict';
// insert - puts a number in the right spot in an array in ascending order
// Parameters are the number to add and the ordered array
const insert = (n, arr) => {
// Make a clean copy of the array
const copy = [...arr];
// Loop through
for (let i = 0; i < copy.length; i++) {
// Put n into the array before the first entry that is
// greater than or equal to it
if (n <= copy[i]) {
copy.splice(i, 0, n);
return copy;
}
// If the function hasn't returned by the end of the loop,
// n is greater than the others and goes at the end
if (i === copy.length - 1) {
copy.splice(i + 1, 0, n);
return copy;
}
}
// Fallback
return copy;
};
// Tests
console.log(insert(3, [1, 2, 4])); // [1, 2, 3, 4]
console.log(insert(5, [1, 2, 4])); // [1, 2, 4, 5]
console.log(insert(2, [1, 2, 4])); // [1, 2, 2, 4]
// insertionSort - implement insertion sort
// uses the insert function
const insertionSort = array => {
// clean copy
const copy = [...array];
// an array that starts with a single item
let sorted = [array[0]];
// loop through the copy, ignoring the item already in sorted
for (let i = 1; i < copy.length; i++) {
// insert each copy item into the sorted array, in order,
// using the insert function
sorted = insert(copy[i], sorted);
}
// return sorted array
return sorted;
};
// Tests
console.log(insertionSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]));
// [1, 1, 2, 2, 4, 8, 32, 43, 55, 63, 92, 123, 123, 234, 345, 5643]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment