我試圖通過我的測試儀通過我的快速排序的實施;不過,我得到數組索引-1越界異常對受表彰的線快速排序升序
public void quickSort(ArrayList<String> data, int firstIndex,
int numberToSort) {
if (data.size() < 16) {
insertionSort(data, firstIndex, numberToSort);
} else {
int index = partition(data, firstIndex, numberToSort);
if (firstIndex < index - 1)
quickSort(data, firstIndex, index - 1);
if (numberToSort > index)
quickSort(data, index, numberToSort);
}
}
@Override
public int partition(ArrayList<String> data, int firstIndex,
int numberToPartition) {
String pivot = data.get(firstIndex);
int left = data.indexOf(firstIndex);
int right = data.indexOf(numberToPartition);
while (left <= right) {
while (data.get(left).compareTo(pivot) < 0) // this is where I get the error
left++;
while (data.get(right).compareTo(pivot) > 0)
right--;
if (left <= right) {
temp = data.get(left);
Collections.swap(data, left, right);
data.set(right, temp);
left++;
right--;
}
}
return left;
}
我試圖調試我的代碼,但似乎我只是不明白的方式來修復錯誤。任何幫助,將不勝感激。
''如果indexOf'''找不到任何東西,則返回-1。 –
顯然'left'是-1 –
看來你正在減少'right'直到'right == - 1',因此'data.get(right)'拋出'java.lang.ArrayIndexOutOfBoundsException:-1' –