-2

显然排序方法导致了stackoverflowerror。为什么?

    public static void quickSort(int[] a, int low, int high) {
        if (a.length > 1) {
            int middle = a.length / 2;
            int size = a.length - middle;
            int pivot = a[middle];

            sort(a, low, middle, high);
            quickSort(a, low, middle);
            quickSort(a, middle + 1, high);
        }
    }

    public static void sort(int[] a, int low, int middle, int high) {
        boolean b = true;

        int i = low;
        int j = high;
        for (int x = 0; x < middle + 1; x++)
            if (a[x] <= a[middle])
                i++;
        for (int x = middle + 1; x < high + 1; x++)
            if (a[x] > a[middle])
                j--;
        if (i != middle && j != middle + 1) {
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            b = false;
        }
        if (b == false)
            sort(a, low, middle, high);
        return;
    }
}
4

1 回答 1

0

请注意这里的排序功能。

if (b == false) {
  sort(a, low, middle, high);
}

这个 b 总是假的。并且你没有改变低、中、hifg 值。所以排序函数调用递归。所以根本没有变化,函数调用重复和stackoverflow会发生。

于 2013-11-12T07:44:20.917 回答