2014-11-16 99 views
-2

此程序显示编译错误,有人可以建议有什么问题吗?使用java快速排序

主类:

import java.util.Scanner; 
public class Sortingpro { 
    public static void main(String[] args) { 
     Scanner input=new Scanner(System.in); 
     System.out.println("Enter the number of elements"); 
     int a=input.nextInt(); 
     int A[]=new int[a]; 
     System.out.println("Enter the elements"); 
     for(int i=0;i<a;i++){ 
      A[i]=input.nextInt(); 
     } 
     sort quick=new sort(A,a); 
     quick.display(A,a); 
    } 
} 

分选类:

public class sort { 
    int A[],size; 
    sort(int a[],int s){ 
     this.A=a; 
     this.size=s; 
     quickSort(a,1,s); 
    } 
    void quickSort(int a[],int p,int r){ 
     while(p<r){ 
      int q; 
      q=Partition(A,p,r); 
      quickSort(A,p,q-1); 
      quickSort(A,q+1,r); 
     } 
    } 

    int Partition(int a[],int p,int r) 
    { 
     int x=a[r]; 
     int i=p-1; 
     for(int j=p;j<r;j++){ 
      if(a[j]<=x){ 
       i+=1; 
       int temp=a[i]; 
       a[i]=a[j]; 
       a[j]=temp; 
      } 
     } 
     int temp=a[i+1]; 
     a[i+1]=a[r]; 
     a[r]=temp; 
     return i=1; 
    }; 
    void display(int A[],int size){ 
     this.A=A; 
     this.size=size; 
     for(int i=0;i<size;i++){ 
      System.out.println(A); 
     } 
    } 

} 

异常。

*****The sorting algorithm used is from CLRS. 
     I am getting the following errors through Netbeans: 
     Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 
     at sortingpro.sort.Partition(sort.java:31) 
     at sortingpro.sort.quickSort(sort.java:23) 
     at sortingpro.sort.<init>(sort.java:17) 
     at sortingpro.Sortingpro.main(Sortingpro.java:26) 

     Can you please elaborate on these errors and the remedial methods to be undertaken to solve     the problem? Also any better methods to implement this program,coding wise? 

对算法的任何建议也是受欢迎的。但是我更喜欢要维护的程序的本质。


+1

异常不是“编译错误”。这意味着它必须编译。 – weston

+0

你在sortpro.sort.Partition(sort.java:31)处有一个执行异常'ArrayIndexOutOfBoundsException'。您正在尝试访问阵列中负数或大于数组的索引。 –

+0

如果您Google“ArrayIndexOutOfBoundsException”并查看堆栈跟踪中指出其编号的行,问题的性质应该变得清晰。 – NPE

回答

2

这是堆栈跟踪说:

你叫快速排序,最大大小一样,如果我进入了10个元素,你叫s的10

quickSort(a,1,s); 

这反过来又要求

q=Partition(A,p,r); 

随着r为10,其依次使用阵列[r]

现在数组以索引0开始,并且一直持续到r-1,因此您将得到ArrayIndexOutOfBound异常。于是打电话与S-1作为最后一个参数的快速排序法,0为开始的索引即

quickSort(a,0,s-1); 

另外在你的递归解决方案,您使用while循环应该是如果。因此,您的快速排序变为:

void quickSort(int a[],int p,int r){ 
    if(p<r){ 
     int q; 
     q=Partition(A,p,r); 
     quickSort(A,p,q-1); 
     quickSort(A,q+1,r); 
    } 
} 
+0

这将抛出StackOverflow – Xline

+0

这是后续行动。 OP的问题是为什么AIOOB不是错误的逻辑或什么,你不能指望看到现场背后的未来或逻辑。 – SMA

+0

谢谢你shaikh :) – Xline