-3

I am receiving java.lang.ArrayIndexOutOfBoundsException: 10 after running this code.

How can I limit my code to only 9 index values or find an alternative way to correct this?

int p = theArray[first]; // use the first item of the array as the pivot p      
int lastS1 = first;      // set S1 and S2 to empty

// ToDo: Determine the regions S1 and S2
// Refer to the partition algorithm on page 495 of the textbook.

for (int i = lastS1; i < last; i++)
    if (theArray[i] < p) {
        for (int j = i ; j > 0 && j >= p ; j--)
            swap(theArray, j, j - 1);
    }

lastS1++;

return lastS1;
sg7
  • 5,365
  • 1
  • 30
  • 39

1 Answers1

0

You can use for (int i = lastS1; i < last - 1; i++).

You need to use last - 1 because in Java, arrays are 0 indexed. Means they start from 0 and go to length - 1.

clinomaniac
  • 2,202
  • 2
  • 15
  • 22
  • While this might prevent the exception, would you please add a slightly more detailed explanation why you think that this implements the intended behavior of the algorithm? – Andrey Tyukin Mar 09 '18 at 00:23