此程序显示编译错误,有人可以建议有什么问题吗?使用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?
对算法的任何建议也是受欢迎的。但是我更喜欢要维护的程序的本质。
异常不是“编译错误”。这意味着它必须编译。 – weston
你在sortpro.sort.Partition(sort.java:31)处有一个执行异常'ArrayIndexOutOfBoundsException'。您正在尝试访问阵列中负数或大于数组的索引。 –
如果您Google“ArrayIndexOutOfBoundsException”并查看堆栈跟踪中指出其编号的行,问题的性质应该变得清晰。 – NPE