我正在编写一个快速排序程序,以在 100000 的输入大小上运行。我尝试以 500 的大小运行它,它工作正常,但有数百万个输入,程序因以下错误代码而中断
“java.lang.StackOverflowError”
有人可以帮我解决这个问题吗?我很确定我没有陷入无限递归。有一个基本情况应该导致递归方法返回。
public class count_comparisons {
public static int count_comp =0;
public static int partitioning(int[] A, int lo, int hi) {
int pivot = A[lo];
int i=lo+1;
int j=lo+1;
int k=lo;
for ( j=lo+1;j<=hi;j++) {
if (A[j] < pivot) {
swap(A,i,j);
i++;
}
}
swap(A,i-1,lo);
return i-1;
}
public static int quicksort(int[] A, int lo, int hi) {
if (lo>=hi) return 0;
int pivot = partitioning(A,lo,hi);
//StdOut.println("Pivot index is "+ pivot +" and entry at pivot is " + A[pivot]);
StdOut.println("Lo is "+ lo +" and Hi is " + hi);
int h = quicksort(A,lo,pivot-1);
int m = quicksort(A,pivot+1,hi);
//StdOut.println("First half count is "+h);
//StdOut.println("Second half count is "+m);
count_comp = count_comp + h + m;
return (hi-lo);
}
public static void quicksort(int[] A,int N) {
int k = quicksort(A,0,N-1);
count_comp = count_comp + k;
//StdOut.println(" First count is "+k);
}
private static void swap(int[] A, int j,int k) {
int temp = A[j];
A[j] = A[k];
A[k] = temp;
}
public static void main(String[] args) {
In in = new In("input_file.txt");
int N=569;
int[] A = new int[569];
int i=0;
while (!in.isEmpty()) {
A[i++] = in.readInt();
}
count_comparisons.quicksort(A,N);
for( int h=0;h<N;h++) {}
//StdOut.print(A[h]);
StdOut.println();
StdOut.println(count_comparisons.count_comp);
}
}