# Help With Sorting Array Please!

• 04-22-2014, 07:32 AM
Bit_Void
I'm making a method to take an array of integers and rearrange the numbers from least to greatest, using for loops. I'm getting the error "java.lang.ArrayIndexOutOfBoundsException: 8," and I don't know why. What should I do to fix the code?

Portion of the ArrayMethods class with the sorting method
Code:

```public static Integer[] sortArray (Integer[] a)   {       int swap;             for (int i = 0; i < a.length; i++)       {                   for (int j = 1; j < a.length; j++)           {               int x = j + 1;               if (a[j] > a[x])               {                   swap = a[j];                   a[j] = a[j+1];                 a[j+1] = swap;                                                 }           }                 }       return a;         }```
Portion of the Driver that uses the code
Code:

```import java.util.Arrays; public class ArrayMethodsDriver {   public static void main(String[] args)   {     Integer[] a = {7,8,8,3,4,9,8,7};         System.out.println(Arrays.toString(ArrayMethods.sortArray(a)));   } }```
Upon running, if (a[j] > a[x]) is highlighted.

Thanks a ton for any help.
• 04-22-2014, 07:44 AM
kneitzel
Re: Help With Sorting Array Please!
Hi,
Your loop with j goes from 1 to array length-1 and then you add 1 for variable x.
So your x value goes from 2 to array length.
But the elements in an array go from 0 to length-1 only, you cannot access an element length.
E.g. an array with 3 elements has the elements 0,1 and 2.

• 04-22-2014, 06:07 PM
jim829
Re: Help With Sorting Array Please!
Similarly, you are ignoring your 0th value in the sort.

Regards,
Jim
• 04-22-2014, 07:19 PM
JosAH
Re: Help With Sorting Array Please!
... also, your sort method compares too many elements (so it is slower than it has to be; check your loops).

kind regards,

Jos