我从现在开始就一直停留在此...数组未正确排序,并且末尾没有递减,有人可以帮我解决我在这里犯的错误吗? 我尝试并寻找了几个小时,但找不到确切的错误。您可以在输出中清楚地看到end没有递减并且数组的排序不合适,因为17是倒数第二个元素,而45是倒数第二个元素。另外还有ArrayOutOfBounds的错误。
代码:
public class Program{
public static void main(String[] args) {
int [] ar={4,5,6,3,10,12,45,17};
int l=0;
int h=ar.length-1;
quickSort(ar,l,h);
}
static void quickSort(int [] arr,int lb,int ub){
int z;
if(lb<ub){
z=partition(arr,lb,ub);
quickSort(arr,z-1);
quickSort(arr,z+1,ub);
}
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
static int partition(int [] a,int ub){
int pivot=a[lb];
int start=lb;
int end=ub;
//If I put end=ub-1 here then it shows index-1.
//so I have not options left to do that the Error is coming eitherway.
System.out.println("start is "+start);
System.out.println("End is "+end);
while(start<end){
while(a[start]<=pivot){
start++;
}
while(a[end]>pivot){
end--;
}
if(start<end){
int temp0=a[start];
int temp1=a[end];
a[start]=temp1;
a[end]=temp0;
}
}
int temp2=a[lb];
int temp3=a[end];
a[lb]=temp3;
a[end]=temp2;
return end;
}
}
output:
start is 0
End is 7
3
4
6
5
10
12
45
17
start is 2
End is 7
3
4
5
6
10
12
45
17
start is 4
End is 7
3
4
5
6
10
12
45
17
start is 5
End is 7
3
4
5
6
10
12
45
17
start is 6
End is 7
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 8
at Program.partition(Program.java:35)
at Program.quickSort(Program.java:16)
at Program.quickSort(Program.java:18)
at Program.quickSort(Program.java:18)
at Program.quickSort(Program.java:18)
at Program.quickSort(Program.java:18)
at Program.main(Program.java:9)