Consider the code for insertion sort we covered in class:
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i];
var j;
for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1];
}
arr[j] = val;
}
return arr;
}
Change this function such that it works from the end of the array rather than
the beginning, insertionSortReverse()
-- only the direction of
iterating over the elements is reversed, the array is still sorted the same way
(ascending). Add your code in code.js
. Test your new function; I've provided
some basic testing code that uses jsverify in
code.test.js
.
In the lectures, we covered that insertion sort has best-case time complexity of
Hint: Think about what happens in each iteration of the loop, and how often the loop is executed. Keep in mind that for asymptotic analysis we don't care about constant factors.
Describe your reasoning and the conclusion you've come to. Your reasoning is most important -- you can easily find the answer, but you need to demonstrate that you've understood the concept. Add your answer to this markdown file.