Insertion Sort - Part 2

  • + 2 comments

    Hi. The problem is with this line of your code:

    while(ar[k]>temp&&k>=0)
    

    It evaluates the expression inside the () from left to right. So it first tries to do ar[k], where k is -1 and it gets an Index Out of Bounds Exception. To fix it, you can change it to

    while(k >= 0 && ar[k] > temp)
    

    Now, it will check for k >= 0 first. If it's not greater than 0, the next expression (to the right of &&) will not evaluate.

    This is called short circuit evaluation

    HackerRank solutions.