簡體   English   中英

快速排序算法因 StackOverflow 錯誤而失敗

[英]Quicksort algorithm fails on StackOverflow error

我正在研究 Quicksort 的修改版本,它使用((lowIndex + highIndex) / 2)的公式來決定它的分區。

我的代碼如下。 但是,每當我運行它時,都會出現以下錯誤:

start ARRAY
1
2
10
9
3
4
8
7
5
6
Exception in thread "main" java.lang.StackOverflowError
        at newQuickSort.quicksort(newQuickSort.java:37)
        at newQuickSort.quicksort(newQuickSort.java:39)

at newQuickSort.quicksort(newQuickSort.java:39)處重復的行。

從本質上講,我只是試圖將分區函數更改為使用三中值分區,而根本沒有真正觸及快速排序算法,只是分區函數。

雖然我參考了以下內容,但我不確定為什么會發生此錯誤:

任何建議都會有所幫助,謝謝!

public class newQuickSort{ 

    static int count;

    static void move(int myArray[], int a, int b){
        int temp;
        temp = myArray[a];
        myArray[a] = myArray[b];
        myArray[b] = temp;
    } //end move

    //Create the partition function
    static int partition(int myArray[], int p, int r){
        int medIndex = (p+r) / 2;
        int pivot;

            if (myArray[p] > myArray[medIndex]){
                move(myArray, p, medIndex); 
            }else if (myArray[p] > myArray[r]){
                move(myArray, p, r);
            }else if (myArray[medIndex] > myArray[r]){
                move(myArray, medIndex, r);
            }
            //end if checks

            //now set proper movements
            move(myArray, medIndex, r-1);
            //set pivot
            pivot = myArray[r-1];
            //return pivot for which to partition around
            return pivot;
    } //end partition 

    static void quicksort(int myArray[], int p, int r){ 
        if (p < r){
        checkCount += 1; 
            int partition = partition(myArray, p, r); 
            quicksort(myArray, p, partition-1); 
            quicksort(myArray, partition+1, r); 
        } //end if 
    } //end quicksort

    public static void main (String[] args){
        int testarray[] = {1,2,10,9,3,4,8,7,5,6};
       // int testarray[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
        System.out.println("start ARRAY");
        for (int i = 0; i < testarray.length; i++){
            System.out.println(testarray[i]);
        } //end for

        int p = 0;
        int r = testarray.length-1;
        newQuickSort mySort = new newQuickSort();
        mySort.quicksort(testarray, p, r);

        System.out.println("end ARRAY");
        for (int j = 0; j < testarray.length; j++){
            System.out.println(testarray[j]);
         } //end for

    }
}

您的partition函數返回樞軸的 但是它的調用者( quicksort )正在期待樞軸的索引

遞歸的終止取決於索引范圍內的分區點。

解決此問題后,請考慮優化quicksort以最大程度地減少堆棧使用:

  1. 首先,遞歸對較小的范圍進行排序(在元素較少的意義上)。

  2. 然后循環到以繼續更大的范圍。

這保證了遞歸深度不超過 log 2 N。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM