我試圖實現這種快速排序算法,但即使它編譯正確,我得到一個ArrayIndexOutOfBoundsException
快速排序算法不起作用
public class MyQuickSort {
private int array[];
private int length;
public void sort(int[] inputArr) {
if (inputArr == null || inputArr.length == 0)
return;
this.array = inputArr;
length = inputArr.length;
quickSort(0, length-1);
}
private void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
while (i<=j) {
while (array[i] < pivot) {
i++;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
exchangeNumbers(i, j);
i++;
j++;
}
}
if (lowerIndex < j)
quickSort(lowerIndex,j);
if (j <higherIndex)
quickSort(i, higherIndex);
}
private void exchangeNumbers(int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String a[]) {
MyQuickSort sorter = new MyQuickSort();
int[] input = {10,9,8,7,6,5,4,3,2,1};
sorter.sort(input);
for(int i:input)
System.out.println(i);
}
}
這裏是例外:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at MyQuickSort.quickSort(MyQuickSort.java:23)
at MyQuickSort.sort(MyQuickSort.java:11)
at MyQuickSort.main(MyQuickSort.java:48)
您是否嘗試過調試程序找出你要訪問的這條線是什麼指標? –
http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – SLaks