排序三种球的算法

时间:2015-03-22 08:08:40

标签: algorithm sorting

我们有三种不同类型的N球:红色(r),蓝色(b)和白色(w)。

我需要对它们进行排序,以便红球出现第一,然后是所有白球,最后是所有蓝球。

示例:

在:bwrwrbbrwwrb

string[] arrBalls = { "b", "w", "r", "w", "r", "b", "b", "r", "w", "w", "r", "b" };

输出:rrrrwwwwbbbb

我需要找到线性O(n)算法。

更新: C#代码

 string[] arrBalls = { "b", "w", "r", "w", "r", "b", "b", "r", "w", "w", "r", "b" };
 int index_red = 0;
 int index_blue = arrBalls.Length - 1;

 for (int i = 0; i < arrBalls.Length; i++)
            {
                if (arrBalls[i] == "r" && index_red != i)
                {
                    string TempRed = arrBalls[index_red];
                    arrBalls[index_red] = arrBalls[i];
                    arrBalls[i] = TempRed;
                    if (arrBalls[index_red] == "r")
                    {
                        while(arrBalls[index_red] == "r")index_red++;
                    }
                    else
                    {
                        index_red++;
                    }


                }


                if (arrBalls[i] == "b" && index_blue != i)
                {
                    string TempRed = arrBalls[index_blue];
                    arrBalls[index_blue] = arrBalls[i];
                    arrBalls[i] = TempRed;

                    if (arrBalls[index_blue] == "b")
                    {
                        while (arrBalls[index_blue] == "b") index_blue--;
                    }
                    else
                    {
                        index_blue--;
                    }
                }


            }

1 个答案:

答案 0 :(得分:5)

将三种类型的球中的每一种计算为3个变量。我们假设您计算了R个红球,B个蓝色球和W个红色球。然后输出R "r",然后输出W "w",然后输出B "b"