Get an error when trying to computer the smallest distance between two integers

advertisements

I am trying to calculate the shortest distance between any two numbers in an array that is sorted. I am testing it with the algorithm below but I get the following error directly beneath; Which is stating that my array is out of bounds, so apparently it is trying to access an index that is not in the length of the array? Not sure why as I have the check for the length in the for loop. Does anyone have clue?

public static void getSmallestDistance(int[] integersCount)
{

    int index = 0;

    for(int i = 1; i < integersCount.length; i++  )
    {
        if( Math.abs(integersCount[index] - integersCount[index + 1]) >
        Math.abs( integersCount[i] - integersCount[i + 1]))//line 73 were error is
        {
            index = i;
        }

    }
    System.out.println(index);
}

I get the following error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1000
at ClosestPair.getSmallestDistance(ClosestPair.java:73)
at ClosestPair.main(ClosestPair.java:57)


The problem is that the array's length is integersCount.length the max value of i is integersCount.length - 1, but you use i+1 to index the array, which is out of bounds.

Therefore you need to run i from 0 or 1 (as needed) upto integersCount.length - 2 that means i < integersCount.length - 2 or i <= integersCount.length - 1