简体   繁体   中英

Whats wrong with this QuickSort implementation?

I cannot guess what is wrong with my code. INPUT:10, 7, 8, 9, 1, 5 OUTPUT:5 7 9 8 10 1

public class QuickSort {

    public static void quickSort(int arr[], int p, int r) {

        if (p < r) {
            // System.out.println(p+" "+r);
            int q = partition(arr, p, r);
            quickSort(arr, p, q - 1);
            quickSort(arr, q + 1, r);
        }
    }

    public static int partition(int arr[], int p, int r) {
        int pivot = arr[r];
        int i = p - 1;
        for (int j = p; j < r - 1; j++) {
            // System.out.println("j");
            if (arr[j] <= pivot) {
                i = i + 1;
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
        int temp = arr[i + 1];
        arr[i + 1] = arr[r];
        arr[r] = temp;
        return i + 1;
    }

    static void printArray(int arr[]) {
        int n = arr.length;
        for (int i = 0; i < n; ++i)
            System.out.print(arr[i] + " ");
        System.out.println();
    }
}

Please clarity my doubt,where to change code so that it works fine.

You are not iterating to the end of the loop (last element). Hence the partition function will not seperate the elements correctly as smaller to the left of pivot and larger to the right of pivot.

Your for loop

for (int j = p; j < r - 1; j++) {

change to

for (int j = p; j <= r - 1; j++) {

Now it is working fine. See here Ideone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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