curriculum/challenges/english/blocks/lab-insertion-sort/587d8259367417b2b2512c86.md
In this lab, you will implement the insertion sort algorithm. 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. This algorithm has quadratic time complexity in the average and worst cases.
Objective: Fulfill the user stories below and get all the tests to pass to complete the lab.
User Stories:
insertionSort function.insertionSort function should take an array of integers and return an array with the same integers sorted from least to greatest.insertionSort should be a function.
assert.isFunction(insertionSort);
insertionSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]) should return an array that is unchanged except for order.
assert.sameMembers(
insertionSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]),
[1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
);
insertionSort should return a sorted array (least to greatest).
assert.sameOrderedMembers(
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, 43, 55, 63, 92, 123, 123, 234, 345, 5643]
);
insertionSort([5, 4, 33, 2, 8]) should return [2, 4, 5, 8, 33].
assert.sameOrderedMembers(insertionSort([5, 4, 33, 2, 8]), [2, 4, 5, 8, 33])
insertionSort should not use the built-in .sort() method.
function isBuiltInSortUsed(){
let sortUsed = false;
const temp = Array.prototype.sort;
Array.prototype.sort = () => sortUsed = true;
try {
insertionSort([0, 1]);
} finally {
Array.prototype.sort = temp;
}
return sortUsed;
}
assert.isFalse(isBuiltInSortUsed());
function insertionSort (array) {
for (let currentIndex = 0; currentIndex < array.length; currentIndex++) {
let current = array[currentIndex];
let j = currentIndex - 1;
while (j > -1 && array[j] > current) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = current;
}
return array;
}