Fihop
Fihop

Reputation: 3177

implementation of quicksort

The following quicksort code comes from programming pearls

void qsort3(int l, int u)
{   int i, j;
    DType t;
    if (l >= u)
        return;
    t = x[l];
    i = l;
    j = u+1;
    for (;;) {
        do i++; while (i <= u && x[i] < t);
        do j--; while (x[j] > t);
        if (i > j)
            break;
        swap(i, j);
    }
    swap(l, j);
    qsort3(l, j-1);
    qsort3(j+1, u);
}

In the two-way partitioning part, there is one line:

if (i > j)

My question is can I change this line to:

if(i >= j)

The reason that I think it's OK to do this is that: (i==j) <=> (x[i] == t) so that we don't need to swap x[i] and x[j]. And we just break out the for loop.

The following code of the for loop is swap(l, j). Since x[j] == t == x[l], swap(l, j) has nothing to do with the partition.

Thanks

Upvotes: 0

Views: 272

Answers (1)

I would say that, Yes, you can make that change:

swap(i, j) is unrewarding when i == j, and the next iteration after i == j unconditionally increments i and decrements j and will thus cause the loop to terminate with no change to the array anyway.

Upvotes: 2

Related Questions