荷兰国旗问题(颜色排序问题)


版权声明:本文为博主原创文章,转载请注明出处。
个人博客地址:https://yangyuanlin.club
欢迎来踩~~~~


题目描述

  • Sort Colors

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.
click to show follow up.
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?

题目大意

给定一个有n个对象的数组,数组中有三种颜色,红色、白色和蓝色,对他们进行排序,相同颜色的在一起,排序顺序是(1)红色、(2)白色、(3)蓝色。数组是int类型的数组,在数组中用0表示红色,1表示白色,2表示蓝色。
必能用库排序函数。

思路

题目中给出了一种思路是,遍历两次数组,第一次遍历统计其中0、1、2的个数,第二次遍历把数组中的值按照0、1、2的个数重新覆盖。
但这种方法不可取,用只用一次遍历的做法来做。
问题就成了荷兰国旗问题:

  • ”荷兰国旗难题“问题描述

”荷兰国旗难题“是计算机科学中的一个程序难题,它是由Edsger Dijkstra提出的。荷兰国旗是由红、白、蓝三色组成的。

现在有若干个红、白、蓝三种颜色的球随机排列成一条直线。现在我们的任务是把这些球按照红、白、蓝排序。

我的思路如下:
设置3个变量,分别代表数组前部zeroindex,当前遍历的位置 i,数组后部 twoindex
(1)当A[i] = 0时,必然属于数组前部,则交换A[i] 和 A[zeroindex] ,接着i++ , zeroindex++
(2)当A[i] = 1时,只需i++就好,因为只有排好了0和2,1自然就只能在中间了,故不作处理
(3)当A[i] = 2时,不然属于数组后部,则交换A[i]和A[twoindex],接着twoindex--,不过此时就不能i++了,因为,交换过去的A[i]有可能是0或者2,所以需要在下一个循环里判断,这样它的位置才能够正确。

代码

#include<iostream>
using namespace std;

void sortColors(int A[], int n)
{
    int start = 0;
    int end = n-1;
    int current = 0;
    while(current <= end)
    {
        if(A[current] < 1)
        {
            swap(A[current++], A[start++]);
        }
        else if(A[current] > 1)
        {
            // 交换过去的current有可能是0或者2
            // 所以得在下次循环判断
            swap(A[current], A[end--]);
        }
        else
        {
            current++;
        }
    }
}

int main()
{
    int A[] =
    {
        0, 1, 2,
        0, 2, 1,
        1, 0, 2,
        1, 2, 0,
        2, 0, 1,
        2, 1, 0
    };
    sortColors(A, 18);
    for(int i=0; i<18; i++)
    {
        cout<<A[i]<<' ';
    }
    cout<<endl;
    return 0;
}

以上。


版权声明:本文为博主原创文章,转载请注明出处。
个人博客地址:https://yangyuanlin.club
欢迎来踩~~~~


©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容