I have the following code below, the value that is being passed in is 4, 1, 9, 14, 6 ,8 and the value which is assigned to newHeight is 1, 4, 6, 8, 9, 14. Insertion Sort sorts the array in ascending order.
var heightChecker = function(heights) {
var sorted = [...heights];
var newHeight = insertionSort(heights);
var count = 0;
for(var i = 0; i < newHeight.length; i++) {
if(newHeight[i] !== sorted[i]) {
count++;
}
}
return count;
}
insertionSort sorts the array, and when i use this line of code
var sorted = [...height];
Then it returns the answer I was looking for which is 3. However when i change the code to be
var heightChecker = function(heights) {
var newHeight = insertionSort(heights);
var count = 0;
for(var i = 0; i < heights.length; i++) {
if(newHeight[i] !== heights[i]) {
count++;
}
}
return count;
}
It returns the answer as 0.
I am not understanding why it isn't the same answer, and after debugging and google searching, I still cannot find why.
Here is the insertion sort code
function insertionSort(inputArr) {
let n = inputArr.length;
for (let i = 1; i < n; i++) {
// Choosing the first element in our unsorted subarray
let current = inputArr[i];
// The last element of our sorted subarray
let j = i-1;
while ((j > -1) && (current < inputArr[j])) {
inputArr[j+1] = inputArr[j];
j--;
}
inputArr[j+1] = current;
console.log(inputArr);
}
return inputArr;
}