Search code examples
javaindexoutofboundsexception

I am trying to build a java sorter, but I keep getting an error


public class Sorter{
  public static void main(String[] args) {
    int[] arr = {9, 3, 5, 6, 2, 2, 53, 5, 75, 78, 68, 6, 5, 44, 5, 63356, 242, 25};

    for (int i = 0; i < arr.length; i++) {
      int minIndex = i;

      for (int j = i + 1; i < arr.length; j++) {
        if (arr[j] < arr[i]) {
          minIndex = j;
        }
      }

      int temp = arr[i];
      arr[i] = arr[minIndex];
      arr[minIndex] = temp;
    }
  }
}

It is supposed to sort the array, but I get this error. I am really confused what to do. I am trying to use the selection sort algorithm.:

java.lang.ArrayIndexOutOfBoundsException: 18
   at Sorter.main(Sorter.java:8)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
   at java.lang.reflect.Method.invoke(Unknown Source)
   at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

Solution

  • In line

    for (int j = i + 1; i < arr.length; j++)
    

    you should change the condition to j < arr.length (replace i with j). and your sort code has another problem too. the line you wrote an if-statement for check j index of arr are smaller or not. you should change the condition to arr[j] < arr[minIndex] (replace i with minIndex).

    The code after this edits should be this.

    public static void main(String[] args) {
        int[] arr = {9, 3, 5, 6, 2, 2, 53, 5, 75, 78, 68, 6, 5, 44, 5, 63356, 242, 25};
    
        for (int i = 0; i < arr.length; i++) {
            int minIndex = i;
    
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
    
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    
        System.out.println(Arrays.toString(arr));
    }
    

    Output:

    [2, 2, 3, 5, 5, 5, 5, 6, 6, 9, 25, 44, 53, 68, 75, 78, 242, 63356]