Bentley-Mcilroy 设计了一种 3 路分区算法,其运行方式有点像这样(基于第一个元素进行分区。最初i = p = 0
和j = q = n-1
):
Scan i from left to right so long as a[i] < a[lo].
Scan j from right to left so long as a[j] > a[lo].
Exchange a[i] with a[j].
If a[i] == a[lo], exchange a[i] with a[p] and increment p.
If a[j] == a[lo], exchange a[j] with a[q] and decrement q.
只要i <= j
. 一旦打破,
Scan j and p from right to left and exchange a[j] with a[p].
Scan i and q from left to right and exchange a[i] with a[q].
现在我想修改它,而不是围绕第一个元素对其进行分区,我可以根据任何外部元素对它进行分区,比如一个整数pivot
(它可能pivot
与数组中的一个元素相同,可能是第一个一个也!)。我怎样才能做到这一点?我尝试通过设置p
为-1而不是0来做到这一点,但不起作用!