Search code examples
javafor-looparraylistindexoutofboundsexceptionquicksort

IndexOutOfBounds: Why does low keep going past high


I keep getting an IndexOutOfBounds error for the if statement down below and I don't know why. low is initially 0, high is set to 24, and the size of the ArrayList is 25.

        for(int i = low + 1; low <= high; i++){
                if(list.get(i).compareTo(list.get(pivIndex)) < 0){ //this line
                E temp = list.get(pivIndex);
                list.remove(pivIndex);
                list.add(pivIndex, list.get(i));

                list.remove(i);
                list.add(i, temp);
            }
        }

Solution

  • You are not bounding i. Your for-loop condition says low <= high, but neither of those variables is being updated in the loop. Meanwhile, i gets larger until it's too big, and that causes the exception.