繁体   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