该程序在编译时显示错误,有人可以提出问题吗?
主要类:
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?
也欢迎对算法提出任何建议。但是我更愿意维护程序的本质。