快速排序java实现

7kjnsjlb  于 2021-11-02  发布在  Java
关注(0)|答案(2)|浏览(395)

我试图实现快速排序算法,但我有困难做它。我认为问题是在分区方法中,我把数组的第一个元素作为枢轴,并且我使用一个指针,它把所有较小的值放在数组的左边,最后把枢轴放在中间。谢谢您。
我的输入是:{42,12,52,1,34,31,0,3}但是我得到了:12,31,1,42,0,3,52,34

public static void quickSort(int[] A) {
        quickSort(A, 0, A.length - 1);
    }

    private static int[] quickSort(int[] A, int low, int high) {
        if (low < high) { // if there is still at least 1 element left in the array
            int p = partition(A, low, high);
            quickSort(A, low, p - 1);
            quickSort(A, p + 1, high);
        }
        return A;
    }

    private static int partition(int[] A, int low, int high) {
        int pointer = low + 1;
        int temp = 0;

        for (int i = low + 1; i <= high; i++) {
            if (A[i] < A[low]) {    // if a num is less than pivot, then put to left
                temp = A[pointer];
                A[pointer] = A[i];
                A[i] = temp;
                pointer++;
            }
            temp = A[pointer - 1];
            A[pointer - 1] = A[low];
            A[low] = temp;
        }
        return pointer - 1;
    }
dohp0rv5

dohp0rv51#

哦,我明白了,我只需要把代码的一部分放在for循环的中间。

cidc1ykv

cidc1ykv2#

int pointer = A[high] 并添加 int i = (low - 1) 其中它是较小元素的索引。

void quickSort(int[] A, int low, int high) {
    if (low < high) {
        int p = partition(A, low, high);

        quickSort(A, low, p - 1);
        quickSort(A, p + 1, high);
    }
}

int partition(int A[], int low, int high) {
    int pointer = A[high];
    int i = (low - 1);

    for (int j = low; j < high; j++) {
        if (A[j] <= pointer) {
            i++;

            int temp = A[i];
            A[i] = A[j];
            A[j] = temp;
        }
    }

    int temp = A[i + 1];
    A[i + 1] = A[high];
    A[high] = temp;

    return i + 1;
}

相关问题