Currently, I am in the process of developing a JavaScript file that includes an insertion sort function, a method to validate a sorted array and return true or false, and a reverse insertion sort function that operates from the end of the array index towards the beginning. Below is the code snippet I have been working on:
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;
}
}
function reverseInsertionSort(arr) {
for(var i = arr.length; i > 1; 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;
}
}
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
arr.push(Math.floor(Math.random()*10000)+1);
}
console.log(arr);
var sortedArr = insertionSort(arr);
console.log(sortedArr);
console.log("And with reverse \n");
var reverseSortedArr = reverseInsertionSort(arr);
console.log(reverseSortedArr);
I am currently facing an issue where sortedArr turns out to be undefined when I output it using console.log. It seems like the problem lies in my function being "undefined", although I have clearly defined it above. I'm puzzled by this inconsistency.