最初的parittion版本:HOARE-PARTITION(A, p, r)1 x ← A[p]2 i ← p - 13 j ← r + 14 while TRUE5 do repeat j ← j - 16 until A[j] ≤ x7 repeat i ← i + 18 until A[i] ≥ x9 if i < j10 then exchange A[i] ↔ A[j]11 else return j
改进后的版本:PARTITION(A, p,r)
1 x ← A[r]
2 i ← p - 1
3 for j ← p to r- 1
4 do if A[j] ≤ x
5 then i ← i +1
6 exchange A[i] ↔A[j]
7 exchange A[i + 1] ↔ A[r]
8 return i + 1
改进后有什么变化呢?
1.PARITION只需用一个i指针,x[i]为分割成三个部分。
2.HOARE-PARITION用了两个指针i及j,但未分割成三个区间,而是获得两个区间,X[p...i] <= X[p],X[j...r] >= X[p]。3.左边的部分小于分割主元,而大于j的部分大于分割主元,当while终止时,p<=j<=i<r(假设至少有2个元素),则X[j+1...r]>=X[p], X[1...j] <= X[p].