0

I was writing the merge sort algorithm, and in the merge helper function, I had the following comparison statement:

    function merge(a,b){
        var result = [];
            while(a.length && b.length){
                    result.push(a[0] < b[0] ? a.shift() : b.shift()); // you can't just grab a[0] or b[0] 
        //as it results in a fatal error.
                }
return, etc.
}

Why is it that when instead of 'a.shift()', I typed a[0], it resulted in a fatal error? Is it because you are doing something with something that's also in a conditional clause?

1
  • Guessing that a[0] doesn't remove the entry from a so you end up in an infinite loop that makes result somewhat larger than desirable. Commented Jul 11, 2015 at 23:37

1 Answer 1

1

Checkout the documentation for shift. It removes the first element. So if you only access a[0] and don't remove it then the while loop never exits.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.