有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java快速排序永不停止

我试图实现快速排序算法,但当我运行它时,它从未停止,结果是StackOverflowException

(我知道,像我一样,使用两个堆栈来重新设置数组的范围并不是最有效的方法,但目前这并不重要。)

 private static void quickSort(int[] a, int start, int end) {
        if (start >= end) {
            return;
        }

        int pivot = a[start];
        Stack<Integer> left = new Stack<Integer>();
        Stack<Integer> right = new Stack<Integer>();

        for (int i = start + 1; i <= end; i++) {
            if (a[i] < pivot) {
                left.push(a[i]);
            } else {
                right.push(a[i]);
            }
        }

        int arrayIndex = 0;
        int middle = 0;

        while (left.size() > 0) {
            a[arrayIndex++] = left.pop();
        }

        middle = arrayIndex;
        a[arrayIndex++] = pivot;

        while (right.size() > 0) {
            a[arrayIndex++] = right.pop();
        }

        quickSort(a, start, middle - 1);
        quickSort(a, middle + 1, end);
    }

共 (1) 个答案

  1. # 1 楼答案

     int arrayIndex = 0;
    

    必须由

     int arrayIndex = start;