分区算法



运行此代码后,我收到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;

您可以使用for (int i = lastS1; i < last - 1; i++) .

您需要使用last - 1因为在 Java 中,数组0索引。意味着它们从 0 开始,一直到 1。

最新更新