[英]StackOverFlow error for QuickSort Algorithm
我得到這個代碼的StackOverflowError。 它表示第184/185行,這是我初始化拆分位置的地方(見下文)並調用第一個遞歸的quickSort方法。 我可以看到代碼在退出遞歸時遇到問題,但我不確定它在哪里發生。 每次我調用quickSort時,它都在一個較小的分區上。
import java.util.*;
public class java2{
public static int MAXINT = 10000;
public static int[] intArray = new int[MAXINT];
public static int index;
public static long comparisons;
public static void main(String[] args)
{
System.out.println("SORTING ALGORITHM: Quicksort");
// Create a random array of integers and sort using the CombSort algorithm
// Print the number of items and comparisions
for(index = 10; index <= 10000; index = index * 10)
{
if (index == 10)
for(int i = 0; i < index; i++)
System.out.print(intArray[i] + " ");
comparisons = 0;
generate(intArray, index);
quickSort(intArray, 0, index - 1);
output(comparisons);
}
}
// Generate an array of random values between 0 and 10000
public static void generate(int[] valueArray, int count)
{
Random generator = new Random();
for(int temp = 0; temp < count; temp++)
{
valueArray[temp] = generator.nextInt(MAXINT) + 1;
}
}
// Print the number of values in the array and the number of comparisons
public static void output(long count)
{
System.out.println("Number of values in array: " + index);
System.out.println("Number of comparisons required: " + count);
System.out.println();
}
//Swap the given values and then assign them to the correct place in the array
public static void swap(int[] value, int i, int j)
{
int temp = value[i];
value[i] = value[j];
value[j] = temp;
}
//Implement Quicksort algorithm
public static void quickSort(int[] value, int startIndex, int endIndex)
{
int r = endIndex;
int l = startIndex;
int s;
if (l < r)
{
s = partition(intArray, l, r);
quickSort(intArray, l, s - 1); // StackOverflowError here
quickSort(intArray, s + 1, r);
}
}
//Partition an array into two parts
public static int partition(int[] value, int startIndex, int endIndex)
{
int r = endIndex;
int l = startIndex;
int p = value[l];
int i = l;
int j = r + 1;
while(i < j)
{
while(value[i] < p)
{
i++;
comparisons++;
}
while(value[j] > p)
{
j--;
comparisons++;
}
swap(value, i, j);
}
swap(value, i, j);
swap(value, l, j);
return j;
}
} // end main
以下是一些可以幫助您開始調試的內容。
你沒有發布你的swap
,但它幾乎肯定是不正確的。 你使用它的方式,它的原型將是void swap(int, int, int, int)
,這意味着它不會對value
數組產生任何影響。 嘗試這樣的事情:
public static void swap(int[] value, int i, int j) {
int temp = value[i];
value[i] = value[j];
value[j] = temp;
}
並像這樣使用它:
swap(value, i, j);
接下來,得到長度= 10的情況正確。 在排序之前和之后打印出完整的數組,驗證輸出是否正確。 當我在一個全零數組上運行你的代碼時,我得到一個無限循環。
接下來,如果您仍然遇到問題,請添加打印語句!
通過重構分區方法,問題已得到修復:
public static int partition(int[] value, int p, int r)
{
int x = value[p];
int i = p - 1;
int j = r + 1 ;
while (true)
{
do
{
j--;
comparisons++;
}
while (value[j] > x);
do
{
i++;
comparisons++;
}
while (value[i] < x);
if (i < j)
{
swap(value, i, j);
}
else
return j;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.