java - 快速排序方法给我一个 stackoverflowerror?

标签 java

我有一个快速排序方法,可以按升序对元素进行排序,但似乎不断出现 stackoverflowerror。

出于某种原因,当逻辑对我来说有意义时,它在 while 循环中显示错误。 这是快速排序类的代码:

    public T[] sort(T[] arr, int left, int right)
    {

        int l = left;
        int r = right;

        if (right <= left)
            return null;

        //Find the pivot in the middle
        T pivot = arr[(left + (right - left)) / 2];

        T temp;


        while (l <= r)
        {
            // check values on left are bigger than the pivot
            while (arr[l].compareTo(pivot) < 0)
            {
                l++;
            }
            // check if values are smaller than the pivot
            while (arr[r].compareTo(pivot) > 0)
            {
                r--;
            }

            // l and r have gone past each other swap them
            if (l <= r)
            {
                //swap process
                temp = arr[l];
                arr[l] = arr[r];
                arr[r] = temp;

                // left pointer goes up 1
                // right pointer goes down 1
                l++;
                r--;
            }
        }

        if (left < r)
            sort(arr, left, r);
        if (l < right)
            sort(arr, l, right);
            return arr;
    }

错误好像是指向

//Find the pivot in the middle
    T pivot = arr[(left + (right - left)) / 2];

然后我似乎遇到了很多错误。

最佳答案

我相信您计算的 Pivot 不正确 你应该使用 T pivot = arr[left + (right - left)/2]; 下面是使用中间元素作为枢轴的快速排序程序:

public void quickSort(T arr[],int left, int right){
        int low =left, high = right;
        int pivot = arr[left + (right - left) / 2];

        while(low<=high){
            while (arr[low] < pivot) {
                low++;
            }

            while (arr[high] > pivot) {
                high--;
            }

            if (low <= high) {
                int  temp = arr[low];
                arr[low] = arr[high];
                arr[high] = temp;

                low++;
                high--;
            }

            if (left < high) {
                quickSort(arr,left, high);
            }

            if (low < high) {
                quickSort(arr,low, right);
            }
      }
}

希望对您有所帮助!!

关于java - 快速排序方法给我一个 stackoverflowerror?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58771005/

相关文章:

java - 如何在单个打印中打印两个 webelement?

java - 如何在 Android 的应用程序内切换用户?

java - 带括号的标准电话号码的电话号码正则表达式

java - JAXB - @XMLTransient 字段在返回到 UI 时消失

java - 重定向到youtube以上传可在jsp上使用的视频

java - 添加 Maven 依赖项,目标 java 版本为 1.6 或多个

java - 调试器未在断点 : Websphere in Eclipse 处停止

java - 在 Retrofit2 中传递自定义对象

java - 异常无法处理?

java - Apache Hadoop API 以原子方式创建唯一目录