分区算法

时间:2018-03-08 21:03:16

标签: java recursion

运行此代码后,我收到 java.lang.ArrayIndexOutOfBoundsException:10

如何将代码限制为仅9索引值或找到另一种方法来纠正此问题?

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;

1 个答案:

答案 0 :(得分:0)

您可以使用ALTER INDEX

您需要使用for (int i = lastS1; i < last - 1; i++),因为在Java中,数组被last - 1索引。意味着他们从0开始并进入长度 - 1.