[英]Quicksort Java code going to infinite loop
當我嘗試運行以下快速排序代碼時,它將進入無限循環。最后一次迭代將進入無限循環。
class QuickSort {
public static void main(String[] args) {
int arr[] = {10, 7, 8, 9, 1, 5,2};
QuickSort ob = new QuickSort();
ob.sort(arr, 0,arr.length-1);
for(int s:arr){
System.out.print(" "+s);
}
}
int partition(int[] arr,int l,int h){
int piv = arr[h];
int i=l-1;
for(int j=l;j<=h-1;j++){
if(arr[j] <= piv){
i++;
int temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
int tp = arr[i+1];
arr[i+1]=arr[h];
arr[h]=tp;
return i+1;
}
void sort(int[] arr,int l,int h){
while(l<h){
int p = partition(arr, l, h);
sort(arr, l, p-1);
sort(arr, p+1, h);
}
}
}
如果出現問題,請提供幫助。
代替while
循環,請使用if
條件,如下所示。
if(l<h){
int p = partition(arr, l, h);
sort(arr, l, p-1);
sort(arr, p+1, h);
}
無需在無限的while
循環中遞歸調用排序。 循環是無限的,因為l
和r
在算法中永遠不會改變。
希望這個幫助:)
您已經使用while
在排序方法。 這將導致無限遞歸調用,最終將導致StackOverFlowException
。 如注釋中所建議,這些是常見錯誤,您可以通過調試(或簡單算法的簡單試運行)輕松找到它們。
您只需要在滿足條件(l < h )
的方法sort
每次調用中進行兩次遞歸調用,為此,您需要一個if
條件while
不是while
循環,如下所示。
void sort(int[] arr,int l,int h){
if(l<h){
int p = partition(arr, l, h);
sort(arr, l, p-1);
sort(arr, p+1, h);
}
}
l
和h
在sort()
永遠不變,因此您將始終擁有l < h == true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.