三值排序問題:用三個指針跟蹤
top_bottom:第三個分區的下界,這個指針往後都是第三個分區的值;
bottom_top:第一個分區的上界,這個指針往前都是第一個分區的值,這個指針和middle_top之間的都是第二個分區的值;
middle_top:第二個分區的上界,這個指針和top_bottom之間的元素都是待排序的。
思路挺像快排的。
class Solution {
public:
void sortColors(vector<int>& nums) {
int top_bottom = int(nums.size()), bottom_top = -1, middle_top = 0, temp = 0;
while (middle_top < top_bottom) {
cout << middle_top << " " << top_bottom << endl;
if (nums[middle_top] == 0 && middle_top > bottom_top) {
temp = nums[bottom_top + 1];
nums[bottom_top + 1] = nums[middle_top];
nums[middle_top] = temp;
bottom_top++;
} else if (nums[middle_top] == 2 && middle_top < top_bottom) {
temp = nums[top_bottom - 1];
nums[top_bottom - 1] = nums[middle_top];
nums[middle_top] = temp;
top_bottom--;
} else {
middle_top++;
}
}
}
};
算法在wiki上寫得很清楚,https://en.wikipedia.org/wiki/Dutch_national_flag_problem#Pseudocode
而且上面的僞代碼比這裏實現的好。
procedure three-way-partition(A : array of values, mid : value):
i ← 0
j ← 0
n ← size of A - 1
while j ≤ n:
if A[j] < mid:
swap A[i] and A[j]
i ← i + 1
j ← j + 1
else if A[j] > mid:
swap A[j] and A[n]
n ← n - 1
else:
j ← j + 1