Partition in Java

时间:2015-07-28 22:26:57

标签: java quicksort partition

I am currently going over some lecture notes given by our lecturer with regards to partitioning an array about a pivot point.

The pseudo code solution given by our lecturer seems to make sense until the if statement at the end.

Should it not be the other way around, that is if(R <= L)?

void partition(int L0, int R0, String p)
{
    L = L0;
    R = R0;

    while ( L <= R )
    {
        // left scan
        while ( lt(arr[L], p) )
            L = L + 1;

        // right_scan
        while ( lt(p, arr[R]) )
            R = R-1;

        if ( L <= R )
        {
            exchange(L,R);
            L = L + 1;
            R = R-1;
        }

    }

} // partition

Can someone please explain to me why this is the case?

1 个答案:

答案 0 :(得分:-1)

I believe the code is correct (inspection only). Here's my attempt at an explanation:

The algorithm starts from the ends of the array and repeats scans and possible exchanges until the indices meet in the middle. The left scan skips over all items from the left that are smaller than your pivot value. The right scan skips over all items from the right that are larger than your pivot value. Once you are through the two scans you have L indexing an item larger than the pivot and R indexing an item smaller than the pivot. At that point you can exchange the two items unless L is already larger than R (i.e. they have crossed each other). In that case they are already in the correct order and don't need to be exchanged. On the next test of the outer loop the method will complete.

The only thing I would note is that I would think the test could be L < R as there's not a lot of point doing the exchange when they are the same index. But I'm happy to be corrected on this in the comments if I've missed something.