由外部元素进行3路分区

时间:2012-10-05 19:07:40

标签: algorithm partitioning

有一个由Bentley-Mcilroy设计的三向分区算法,其运行方式与此类似(基于第一个元素进行分区。最初为i = p = 0j = 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,而不是工作!

1 个答案:

答案 0 :(得分:1)

您需要将a[lo]的所有引用替换为pivot