简体   繁体   中英

Why my code doesn't run ? Insertion Sort

Function of insertion sort is not working, Error is : A function is taking too long to run. Perhaps you have a mistake in your code?

// this function
var insert = function(array, rightIndex, value) {
    for(var j = rightIndex;
        j >= 0 && array[j] > value;
        j--) 
    {
        array[j + 1] = array[j];
    }   
    array[j + 1] = value; 
};

var insertionSort = function(array) {
    for(var i = 0; i < array.length ; i++)
    {
        insert(array,i,array[i+1]);
    }
};

var array = [22, 11, 99, 88, 9, 7, 42];
insertionSort(array);
println("Array after sorting:  " + array);
Program.assertEqual(array, [7, 9, 11, 22, 42, 88, 99]);

Your problem is on choosing array position as [i+1] and [j+1]

change

var insert = function(array, rightIndex, value) {
    for(var j = rightIndex;
        j >= 0 && array[j] > value;
        j--) 
    {
        array[j + 1] = array[j];
    }   
    array[j + 1] = value; 
};

into

var insert = function(array, rightIndex, value) {
    for(var j = rightIndex;
            j > 0 && array[j-1] > value;
            j--) 
        {
            array[j] = array[j-1];
        }   
        array[j] = value; 
    };

and

 insert(array, i, array[i+1]);

into

 insert(array, i, array[i]);

 var insert = function(array, rightIndex, value) { for(var j = rightIndex; j >= 0 && array[j] > value; j--) { array[j + 1] = array[j]; } array[j + 1] = value; }; var insertionSort = function(array) { for(var i = 0; i < array.length - 1 ; i++) { insert(array,i,array[i+1]); } }; var array = [22, 11, 99, 88, 9, 7, 42]; insertionSort(array); console.log(array); 

you should run your loop 1 less iteration as you are calling the insert() function with i + 1;

Try going through the array backwards inside the insertionSort function:

var insertionSort = function(array) {
  for (var i = array.length - 1; i >= 0; i--) {
    insert(array,i,array[i+1]); 
  } 
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM