java排序算法中的这个StackOverflowError 怎么改
个快速排序的程序,编译后出错。error如下,不知道怎么改。请大家帮忙提示一下 怎么改我的程序。非常感谢!
Java code?Exception in thread "main" java.lang.StackOverflowError at org.quicksortprac.kql.QuickSort1.<init>(QuickSortApp1.java:13) at org.quicksortprac.kql.QuickSort1.<init>(QuickSortApp1.java:18) at org.quicksortprac.kql.QuickSort1.<init>(QuickSortApp1.java:18) at org.quicksortprac.kql.QuickSort1.<init>(QuickSortApp1.java:18) at org.quicksortprac.kql.QuickSort1.<init>(QuickSortApp1.java:18) at org.quicksortprac.kql.QuickSort1.<init>(QuickSortApp1.java:18) at org.quicksortprac.kql.QuickSort1.<init>(QuickSortApp1.java:18)
代码如下:
Java code?/* Quick Sort Practice * */package org.quicksortprac.kql; class QuickSort1{ // constructor int[] Arr; int p; int r; int q; QuickSort1 qks; public QuickSort1(int[] arr){ Arr = arr; p=0; r= arr.length-1; q=0; qks = new QuickSort1(arr); } public void sortingArray(int[] arr, int p, int r){ QuickSort Q = new QuickSort(arr); q = qks.partition(p, r); Q.sortingArray(arr, q+1, r); Q.sortingArray(arr, q+1, r); } //------------------------------------ public int partition(int p, int r){ int i, j; i= p-1; for(j=p; j<r; j++){ if(Arr[j]<Arr[r]){ i++ ; int tp = Arr[i]; // A[i] <---> A[j] Arr[i] = Arr[j]; Arr[j]= Arr[tp]; } } int temp = Arr[i+1]; Arr[i+1] = Arr[j]; Arr[j] = temp; return i+1; }// end method //----------------------------- } // end classQuickSort //================================================ public class QuickSortApp1 { public static void main(String[] args) { int[] A = {2, 5, 71, 23, 13, 3, 4, 9, 30}; QuickSort sort = new QuickSort(A); sort.sortingArray(A, 0, A.length-1); for(int i=0; i<A.length-1; i++){ System.out.print(A[i]+" "); } System.out.println(); } } public QuickSort1(int[] arr){ Arr = arr; p=0; r= arr.length-1; q=0; qks = new QuickSort1(arr); }
里qks在构造函数中new 自己,相当于无限new 自己,死递归了...
试试去掉qks的声明 然后把这句q = qks.partition(p, r);改成q = this.partition(p, r);
|