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.
void sortColors(int* nums, int numsSize)
{
if(numsSize==0||nums==NULL)
return;
if(numsSize==1)
return;
int red=0,white=0,blue=0;
for(int i=0;i<numsSize;i++)
{
if(nums[i]==0)
red++;
if(nums[i]==1)
white++;
if(nums[i]==2)
blue++;
}
for(int i=0;i<numsSize;i++)
{
if(i<red)
{
nums[i]=0;
}
if(i>=red&&i<(red+white))
{
nums[i]=1;
}
if(i>=(red+white)&&i<numsSize)
{
nums[i]=2;
}
}
}
本文介绍了一种不使用标准库排序函数的颜色排序算法。该算法将数组中的红色(0)、白色(1)和蓝色(2)元素按顺序排列在一起。通过计数每种颜色的数量,并重新填充数组来实现。
337

被折叠的 条评论
为什么被折叠?



