最初のものは単純で、反転が見つかるまで両側から歩くだけです。
/*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;
}
}
2 つ目 (「アルゴリズムの紹介 」に示されています) は次のとおりです。
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;
}
2 つ目の不変条件は、「バインド前のすべての要素がピボットより小さい」です。
Q: 2 つのバージョンの長所と短所は何ですか?
最初に 1 つを与え、2 つ目はイテレーター (ポインター) で ++ 操作を必要とするためForwardIterator
、リンクされたリストのイテレーターのようなものに適用できます。その他のヒントは?