简体   繁体   English

快速排序降序而不是升序

[英]Quick Sort Sorts Descending Not Ascending

I just implemented QuickSort algorithm from book and got weird output.我刚刚从书中实现了 QuickSort 算法并得到了奇怪的输出。 It works but it sorts in descending order instead of ascending.它有效,但它按降序而不是升序排序。 For example: [1, 5, 2, 10, 6, 9, 8, 3, 7, 4] is sorted [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] cant seem to find source in my code:例如:[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;
        }
    }
}

INITIAL CALL:初次通话:

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

how do i calculate the space complexity for the quicksort?我如何计算快速排序的空间复杂度?

thank you guys谢谢你们

It's in your partition function, you are sorting in descending order.它在您的分区函数中,您正在按降序排序。

 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;
    }
 }

//for ascending: //升序:

 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;
    }
}

The key point to note here is the part where you create the windows of all elements less than pivot and all elements greater than pivot during partitioning.这里要注意的关键点是在分区期间创建所有小于 pivot 的元素和大于 pivot 的所有元素的窗口的部分。 Your implementation is making sure that at the end of the partitioning, left half of the array will have all elements greater than the pivot and right half will have all elements less than pivot.您的实现确保在分区结束时,数组的左半部分将包含大于主元的所有元素,而右半部分将包含小于主元的所有元素。 Just doing the reverse will make it in ascending order只要做相反的事情就会使它按升序排列

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM