![](/img/trans.png)
[英]Calculating the average median of a large array (up to 100,000 elements)
[英]Does anyone know why my quick sort algorithm is getting a stack overflow error on large data sets ex. an array of length 100,000?
我的 Java 快速排序算法在長數組(例如長度為 100,000 的數組)上引發堆棧溢出錯誤。 我正在使用三種方法的中位數找到我的支點。 我有我的中位數(中位數)和快速排序方法(qSortB)。 有誰知道為什么會發生這個錯誤? 謝謝你的幫助。
//Finding the pivot using the median of three method
public int median(int low, int high){
int p;
int temp;
int min= list[low];
//System.out.println("min: "+ min);
int med=list[(high+low)/2];
//System.out.println("med: "+ med);
int max= list[high];
//System.out.println("max: "+ max);
if ((min >= med) != (min >= max)) {
p= min;
}
else if ((med >= min) != (med >= max)) {
p= med;
temp=list[(high+low)/2];
list[(high+low)/2] = list[low];
list[low] =temp;
}
else {
p= max;
temp=list[high];
list[high] = list[low];
list[low] =temp;
}
return p;
}
public void qSortB(int low, int high){
if(low>=high|| high<=low){
return;
}
else{
int left=low+1;
int right=high;
int pivot =median(low,high);
//System.out.println("Pivot: "+ pivot);
int pi=low;
while(left<=right){
while(left <len && list[left]< pivot){
comp++;
left++;
}
while(right >-1 && list[right] >pivot){
comp++;
right--;
}
if(left <len && right>-1 && left<=right){
comp++;
// System.out.println("Swapping "+list[right]
// +" with " + list[left]);
int temp=list[left];
list[left] = list[right];
list[right] = temp;
left++;
right--;
swap++;
//print();
}
if(left>right){
int temp= list[left-1];
list[left-1]= pivot;
list[pi]= temp;
pi=left-1;
swap++;
qSortB(low,pi-1);
qSortB(pi+1,high);
}
}
}
}
當您傳入一個大數組時,您會遇到堆棧溢出錯誤,因為您必須記住您在函數內的位置。 在qSortB()
您再次調用qSortB()
,這意味着您調用了另一個函數,而不是結束前一個函數,因為您必須記住自己的位置,這會占用更多內存,直到導致堆棧溢出。
要解決這個問題,您不需要使用如此大的數組,或者重新編寫函數以使用循環而不是調用自身,這樣函數就會結束,防止堆棧溢出錯誤。
正如 fantaghirocco 提到的,我建議查看此鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.