javascriptarrayssortinginsertion-sort

Insertion Sort from Right to left with Javascript


I am trying to write an insertion sort function that works from right to left. Not in descending order. I just am not understanding why this code would not properly sort numbers.

function reverseInsertionSort(arr) { 
for(var i = arr.length -1; i >0; i--) 
var val = arr[i];
    var j;
    for(j = i; j > 0 && arr[j-1] < val; j--) {
        arr[j-1] = arr[j]; }
     va=arr[j]; }
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; }
    }
            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);
}
var arr2= arr.slice();

reverseInsertionSort(arr2);
console.log(arr2)

It is not sorted, and the output ends in undefined. arr is being used to test the insertionsort fun Happy to accept constructive criticism.


Solution

  • This will work.

    function reverseInsertionSort(arr) { 
    
        for(var i = arr.length-2; i>=0; i--) {
    
            var value = arr[i];
            var j;
    
            for(j = i; ((j < arr.length) && (arr[j+1] > value)); j++){ 
                arr[j] = arr[j+1]; 
            } 
            arr[j] = value;
        }
        return arr;
    }
    
    //test
    var inputArray = [3,2,4,5,1,10,23];
    var resultArray = reverseInsertionSort(inputArray);
    console.log(resultArray); //[23, 10, 5, 4, 3, 2, 1]