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的异常不是很了解,怎么修改才行?

解决方案 »

  1.   

    数组越界
    肯定是在这里面出错
    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]);  
      

  2.   

    while (a[j] > pivot);//前面有int j = r + 1;
      

  3.   

    do 
    {
    j = j - 1;  

    while (a[j] > pivot);  
    先执行了j=j-1不就不越界了吗
      

  4.   

    do 
    {
    i = i + 1;  
    } while (i < j && a[i] < pivot);  
    这样应该就没有问题了
      

  5.   

    给楼主一个例子。
    public class Test
    {
       public static void main(String arge[]){
    int [] num=new int[10];
    num[0]=111;
    num[1]=68;
    num[2]=18;
    num[3]=38;
    num[4]=88;
    num[5]=98;
    num[6]=78;
    num[7]=58;
    num[8]=48;
    num[9]=28;
    //Sort ss=new Sort();
    quicksort(num,0,9);
    for(int a=0;a<num.length;a++)
    System.out.println(num[a]);
    }
    public static void quicksort(int[] r,int low,int high){
    int pivo;
    if(low<high){
    pivo=partition(r,low,high);
    quicksort(r,low,pivo-1);
    quicksort(r,pivo+1,high);
    }
    }
    public static int partition(int[] r,int z,int x){
    int i,j,temp,pivot;
    i=z;
    j=x;
    pivot=r[i];
    while(i<j){
    while(i < j && pivot<=r[j]) j--;
    if(i<j){
    r[i]=r[j];
    i++;
    }
    while(i < j && pivot>=r[i]) i++;
    if(i<j){
    r[j]=r[i];
    j--;
    }
    }//while end
    r[i]=pivot;
    return i;
    }}
      

  6.   

    arsaluo(热血年华) ( ) 
    数组越界
    肯定是在这里面出错
                                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]);  
    -------------------------------------------------
    不懂楼主这段程序是怎么写的?你是不是考虑下在while里试着加个条件
    if(i>=num.length) break;
      

  7.   

    do 
    {
    j = j - 1;  

    while (a[j] > pivot);  
    先执行了j=j-1不就不越界了吗
    ------------------------
    我晕了,你的数组长度是9,j = r + 1; 这时候j=10;
    j=j-1; 这时候j=9;
    num[9]还没越界?