簡體   English   中英

快速排序降序而不是升序

[英]Quick Sort Sorts Descending Not Ascending

我剛剛從書中實現了 QuickSort 算法並得到了奇怪的輸出。 它有效,但它按降序而不是升序排序。 例如:[1, 5, 2, 10, 6, 9, 8, 3, 7, 4] 被排序為 [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 似乎不能在我的代碼中查找源代碼:

private void quicksort(int[] A, int p, int r) {
    if (p < r) {
        int q = partition(A, p, r);
        quicksort(A, p, q);
        quicksort(A, q + 1, r);
    }
}

private int partition(int[] A, int p, int r) {
    int x = A[p]; // pivot
    int i = p;
    int j = r;
    while (true) {

        while (A[i] > x) {
            i++;
        }

        while (A[j] < x) {
            j--;
        }
        if (i < j) {
            int temp = A[i];
            A[i] = A[j];
            A[j] = temp;
        } else {
            return j;
        }
    }
}

初次通話:

   quicksort(A, 0, A.length - 1);

我如何計算快速排序的空間復雜度?

謝謝你們

它在您的分區函數中,您正在按降序排序。

 while(true) {
 //ignore all the numbers greater than X to left
 while (A[i] > x) {
        i++;
    }
 //ignore all numbers lesser than X to right
 while (A[j] < x) {
        j--;
 }

 //swap a number lesser than X on left with a number greater than X on right
    if (i < j) {
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
        i++;
        j--;
    } else {
        //Now the array is so sorted, that all numbers lesser than X are on right of it and greater than X are to left of it. Hence return position of X
        return j;
    }
 }

//升序:

 while(true) {

 while (A[i] < x) {
        i++;
 }

 while (A[j] > x) {
        j--;
 }

    if (i < j) {
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
        i++;
        j--;
    } else {
        return j;
    }
}

這里要注意的關鍵點是在分區期間創建所有小於 pivot 的元素和大於 pivot 的所有元素的窗口的部分。 您的實現確保在分區結束時,數組的左半部分將包含大於主元的所有元素,而右半部分將包含小於主元的所有元素。 只要做相反的事情就會使它按升序排列

 while (A[i] < x) { i++; } while (A[j] > x) { j--; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM