The first one is straightforward, just walk from both sides until finding a reversion.
/*C++ version, [first, last), last needs --first to fetch the last element*/
/*returns the middle of partitioning result*/
int* partition( int *first, int *last, int pivot ) {
while (true) {
while (*first < pivot) ++first;
--last;//Don't edit this, it's true.
while (pivot < *last) --last;
if (!(first < last)) return first;
swap(*first, *last);
++first;
}
}
The second one (shown in "Introduction to algorithms") is:
int* partition( int a[], int n, int pivot ) {
bound = 0;
for ( i = 1; i != n; ++i )
if ( a[i] < pivot )
swap( &a[i], &a[++bound]);
swap(a, a + bound);
return a + bound;
}
The invariant of the second one is " All elements before bound is less than pivot " .
Q: And what is the advantages and disadvantages of the two versions?
I'll give one first, the second one require ++ operation on the iterator( pointer ), so it can be applied to some ForwardIterator
like the iterator of a linked list. Other tips?