简体   繁体   中英

Why this QuickSort Partition method is wrong?

I have a quickSort Partition method. But I don't see why it is wrong

the method is here:

private static <E extends Comparable<E>> int partition(E[] list, int first, int last) {
    int pivotIndex = (first + last) / 2;
    E pivot = list[pivotIndex]; // Choose the first element as the pivot
    swap(list, last, pivotIndex);
    pivotIndex = last;
    last--;
    do {
        // Search forward from left
        while (first < last && list[first].compareTo(pivot) <= 0)
            first++;
        // Search backward from right
        while (first <= last && list[last].compareTo(pivot) > 0)
            last--;

        // Swap two elements in the list
        if (last >= first) {
            swap(list, first, last);
            first++;
            last--;
        }
    } while (last > first);

    swap(list, pivotIndex, first);

    return first;
}

This is how it is called using recursive:

quickSort ( array )
quickSortRec( array, 0, array.size - 1 )
quickSortRec (array, left, right)
pivotIndex = findpivot(array, left, right) //use any method
newPivotIndex = partition ( array, left, right, pivotIndex )
if ( newPivotIndex - left > 1 )
quickSortRec( array, left, newPivotIndex - 1 )
if ( right - newPivotIndex > 1 )
quickSortRec( array, newPivotIndex + 1, right )

I know the bugs lie in the do while loop but I don't know why and how. I don't need the correct version of the partition method... I just want to know why this one is wrong. For example, if I want to sort [12 28 79 19 60 22 3 50 75 60 25 97 98 12 88 ] it gives me [3 12 19 22 25 12 28 50 60 60 75 79 88 97 98] which is wrong...

In the first line,

int pivotIndex = (first + last) / 2;

The pivotIndex now holds the position of middle element.

E pivot = list[pivotIndex];

Now you assign that value to pivot.

Maybe that's why your code is giving you the wrong answer.

It is just placing the elements smaller than 50 (ie middle element) towards its left and larger towards the right.

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