Java中的QuickSort函数提供了StackOverflow

时间:2014-01-22 16:20:12

标签: java quicksort

我知道这不是一个真正的错误测试地点,但我一直试图在我的java快速排序中发现我的错误数小时,我看不到它,所以如果有人能指出我的话我会非常感激的。

以下是示例:

     public class QuickSort {
    public static int partition(int[] a, int start, int end) {

        int piv = a[end];
        int iLeft = start;
        int iRight = end;
        while (iLeft < iRight) {
            while (a[iLeft] < piv) {
                iLeft++;
            }
            while (a[iRight] >= piv) {
                iRight--;
                if (iRight == iLeft) {
                    break;
                }
            }

            if (iLeft < iRight) {
                int val = a[iLeft];
                a[iLeft] = a[iRight];
                a[iRight] = val;
            }

        }
        return iRight;
    }

    public static int[] Sort(int[] a, int start, int end) {
        if (a.length < 2) {
            return a;
        } else {
            int Next_Mid = partition(a, start, end);
            Sort(a, start, Next_Mid);
            Sort(a, Next_Mid + 1, end);
            return a;
        }
    }

    public static void main(String[] args) {
        int[] c = new int[] { 1, 10, 2, 9, 3, 8, 3, 7, 4, 6, 5 };
        Sort(c, 0, c.length - 1);
    }
}

2 个答案:

答案 0 :(得分:4)

由于您的Sort方法永远不会为a创建新的子数组,因此您的退出条件是错误的:如果a以10个元素开头,则它总是有10个元素,所以你的递归永远不会结束。

您需要检查开始和结束索引是否分开两个或更少位置:

if (end-start < 2) {
    return a;
}

答案 1 :(得分:1)

错误很明显:

public static int[] Sort(int[] a, int start, int end) {
  if (a.length < 2) {
    return a;
  } else {
    int Next_Mid = partition(a, start, end);
    Sort(a, start, Next_Mid);
    Sort(a, Next_Mid + 1, end);
    return a;
  }
}

递归只能在数组的长度为&lt; 2,但你总是传递相同的数组。

您可能想要查找end-start或其他内容。