题目:
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
题目大意就是
输入:0 1 1 0 2 1 0 2
输出:0 0 0 1 1 1 2 2
以快排的思路解题
快排的主要思路就是partition 划分,一般来说是划分为两段。快排中的left,right,mid和二分查找的left right mid不同,通过不断的交换,实现排序
class Solution {
public:
void sortColors(vector<int>& nums) {
int n=nums.size();
int left=0,right=n-1;
int index=0;
while(index<=right){
if(nums[index]==0){
swap(nums[left],nums[index]);
left++;
index++;
}
else if(nums[index]==1){
index++;
}
else{
swap(nums[index],nums[right]);
right--;
}
}
}
};