0

I am working on a program that uses a scanner to read a file of 25 integers and save them to an array in order. The method below is looks at the next int in the file (key) and inserts into the array in its sorted position.The method is a lot like the insertionSort method except I can't insert ints into the array out of order and then sort them after, I have to compare them to the already sorted ints in the array and then insert it where it belongs and move everything else one to the right.

The issue I'm having is that when I run it I get the error:

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at Lab3.insertInOrder(Lab3.java:53) at Lab3.main(Lab3.java:26)"

I understand what the error means. My question is why does it seem like my condition "j>0" in the while loop seem to not stop the loop from trying to put an in in arr[-1]?

static void insertInOrder( int[] arr, int count, int key   )
{
    if (count == 0 ) arr[0] = key;
    else if (key >= arr[count-1]) arr[count] = key;
    else if (key < arr[count-1])
    {
        int placeHolder, j=count;
        while (key <= arr[j-1] && j > 0) 
        {
            placeHolder = arr[j-1];
            arr[j-1] = key; 
            arr[j] = placeHolder;                       
            j--;
        }

    }           
}
  • Did you step through the code in your IDE debugger to detect where things deviate from your expectations? – Jim Garrison Feb 03 '18 at 00:37
  • I am not using an IDE. My expectations are just to read in the integers, insert them, sorted, into an array, and then print the array. – Mackenzie Bana Feb 03 '18 at 00:42
  • Not using an IDE is like woodworking with stone tools. If you really want to work in that environment, then liberally scatter print statements in your code to print the values of variables so you can see what the code is doing. – Jim Garrison Feb 03 '18 at 00:47

0 Answers0