-3

This is my code:

       int size, i, j, temp;
       int arr[] = new int[50];
       Scanner scan1 = new Scanner(System.in);

       System.out.print("Enter Array Size : ");
       size = scan1.nextInt();

       System.out.print("Enter Array Elements : ");
       for(i=0; i<size; i++)
       {
           arr[i] = scan1.nextInt();
       }

       System.out.print("Sorting Array using Insertion Sort Technique..\n");
       for(i=1; i<size; i++)
       {
           temp = arr[i];
           j = i - 1;
           while((temp < arr[j]) && (j >= 0))
           {
               arr[j+1] = arr[j];
               j = j - 1;
           }
           arr[j+1] = temp;
       }

       System.out.print("Array after Sorting is : \n");
       for(i=0; i<size; i++)
       {
           System.out.print(arr[i] + "  ");
       }
   }

When I run this an error is displayed:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 50 at ProgramFinals.main(ProgramFinals.java:72)

ItsPete
  • 2,363
  • 3
  • 27
  • 35
Rods
  • 9
  • You allow users to enter arbitrary array size but you have declared its size to be 50, does it make sense? – LHCHIN Dec 02 '19 at 03:31
  • Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Zain Dec 02 '19 at 04:39

2 Answers2

0

the size of the array is already fixed to 50. if a user enters any number greater than that then there will be an ArrayIndexOutOfBoundsException for input number 51 onwards

0

I have 2 tips for you:

1st tip: If you want the user to define the size/length of the array, a good approach could be asking for the dimension/length first and then declaring the array like:

int[] arrayOfInts = new int[requestedDimension];

2nd tip: It makes sense to create a variable for the array's dimension, but it makes even more sense to just use array.length, it's faster and it doesn't require allocating memory for a variable to be used in every for you will create.

About your problem:

The problem is with j, becuase you first declare j as i - 1 (which on the first iteration it makes j = 0), then you compare if j is greater or equal to 0 (which it is) and then you procede to decrease j by 1 which makes it -1 and effectively throwing an ArrayIndexOutOfBounds exception.

j = i - 1;
               while((temp < arr[j]) && (j >= 0))
               {
                   arr[j+1] = arr[j];
                   j = j - 1;
               }

Try making the 2nd condition of the while loop a j > 0.

maurirlz
  • 60
  • 9