关于快速排序
public class QuickSort {
public static void main(String[] args) {
int[] num={2,4,7,9,1,8,3,0,5,6};
quickSort(num,0,9);
for(int i=0;i <10;i++)
System.out.println(num[i]);
}
public static void quickSort(int a[], int l, int r)
{
if (l > = r) return;
int i = l;
int j = r + 1;
int pivot = a[l];
while (true)
{
do
{
i = i + 1;
} while (a[i] < pivot);
do
{
j = j - 1;
}
while (a[j] > pivot);
if (i > = j) break;
swap(a[i], a[j]);
}
a[l] = a[j];
a[j] = pivot;
quickSort(a, l, j-1);
quickSort(a, j+1, r);
}
public static void swap(int x,int y)
{
int temp=x;
x=y;
y=temp;
}
}
总是报错
java.lang.ArrayIndexOutOfBoundsException: 10
at QuickSort.quickSort(QuickSort.java:20)
at QuickSort.quickSort(QuickSort.java:34)
at QuickSort.quickSort(QuickSort.java:34)
at QuickSort.main(QuickSort.java:5)
Exception in thread "main "
对java的异常不是很了解,怎么修改才行?
------解决方案--------------------do
{
i = i + 1;
} while (i < j && a[i] < pivot);
这样应该就没有问题了