我得到此代碼的StackOverflowError。它說184/185行,這是我初始化分割位置(見下面)並調用第一個遞歸quickSort方法的地方。我可以看到代碼在遞歸中退出時遇到了麻煩,但我不確定發生了什麼。每次我打電話給quickSort時,它都在一個較小的分區上。QuickSort算法的StackOverFlow錯誤
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
你可以用一個工作比較你的版本:http://algs4.cs.princeton.edu/23quicksort/Quick.java –
嘗試找到一個非常短的示例,它會崩潰並將部分排序結果與手動執行快速排序時的預期結果進行比較。 – MrSmith42
如果你的算法適用於短陣列,你可能只需要增加堆棧大小。 (對於真實世界的應用程序,您可能會考慮QuickSort的非遞歸版本以避免堆棧probelmatic – MrSmith42