Search code examples
javascriptarraysnode.jssortinginsertion-sort

insertion sort last item undefined


I am practicing hackerrank and want to process a data structure using insertion sort. Given the type String data structure:

6
1 4 3 5 6 2

I want to count from index starting at value 1, so counting index 0 the array's size, and new line character, I should start at 2. I want to at every loop log the output of each step of shifting the array index left or right.

function processData(input) {     
    function sort(input) {
        let values = input.split('\n')
        values = values[1].split(' ').map(i => parseInt(i));        
        var length = values.length;
        for(var i = 1; i < length; i++) {          

            console.log('input sort', values[i])
            var temp = values[i] === undefined ? null: values[i];
            var j = i - 1;
            for(j; j >= 0 && values[j] > temp; --j) {
                values[j+1] = values[j];    
            }
            values[j+1] = temp;
            var result = values.join(" ");

            console.log(values);
       }
       // return values;
   };
};

my output is below. Notice the trailing undefined. I'm still new to these sorting algorithms and I'm hoping someone can explain where that is coming from.

input sort 4
[ 1, 4, 3, 5, 6, 2 ]
input sort 3
[ 1, 3, 4, 5, 6, 2 ]
input sort 5
[ 1, 3, 4, 5, 6, 2 ]
input sort 6
[ 1, 3, 4, 5, 6, 2 ]
input sort 2
[ 1, 2, 3, 4, 5, 6 ]
undefined

I would like an output without the undefined character.

[ 1, 4, 3, 5, 6, 2 ]
input sort 3
[ 1, 3, 4, 5, 6, 2 ]
input sort 5
[ 1, 3, 4, 5, 6, 2 ]
input sort 6
[ 1, 3, 4, 5, 6, 2 ]
input sort 2
[ 1, 2, 3, 4, 5, 6 ]

Solution

  • This has nothing to do with your algorithm.

    You see that part at the very end that looks like:

       // return values;
    

    Delete the //.

    You are getting undefined on the last line because the function has no return value and you are running it in a console. It's not coming from one of your console.log statements, but from the default console behavior of printing out the result of the last line that executed. In this case, that last line is a function with no value that yields undefined.