Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Description Title:
Given a red, white and blue, a total of n elements of the array, sorts them in situ, such that adjacent elements with the same color and arranged in a red, white, blue order.
This question, we use an integer of 0, 1 and 2 represent the red, white and blue.
Note:
You can not use the sort function code base to solve this question.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
1, bubble sort
class Solution {
public:
void sortColors(vector<int>& nums) {
if(nums.empty())
return ;
int n=nums.size();
for(int i=n-1;i>0;i--){
bool flag=false;//标记,如果本轮没发生交换,则有序,不需要再排
for(int j=n-1;j>n-1-i;j--){//每次都是从最后往前比较
if(nums[j]<nums[j-1]){
flag=true;
swap(nums[j],nums[j-1]);
}
}
if(flag==false)
return ;
}
}
};