Skip to content
Advertisement

Quick Sort Sorts Descending Not Ascending

I just implemented QuickSort algorithm from book and got weird output. 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:

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

Advertisement

Answer

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;
    }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement