zhanggl

何谓荷兰国旗:

现有红、白、蓝三个不同颜色的小球,乱序
排列在一起,请重新排列这些小球,使得红
白蓝三色的同颜色的球在一起。这个问题之
所以叫荷兰国旗,是因为我们可以将红白蓝
三色小球想象成条状物,有序排列后正好组
成荷兰国旗。

 

问题转换为:给定数组A[0…N-1],元素只能取0、
1、2三个值,设计算法,使得数组排列成
“00…0011…1122…22”的形式。
 借鉴快速排序中partition的过程。定义三个指针:
begin=0、current=0、end=N-1:
 A[cur]==2,则A[cur] 与A[end]交换,end--,cur不变
 A[cur]==1,则cur++,begin不变,end不变
 A[cur]==0,则:
 若begin==cur,则begin++,cur++
 若begin≠cur,则A[cur]与A[begin]交换,begin++,cur不变

 

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

void  Holland(int* a, int length)
{
    int begin = 0;
    int currentNum = 0;
    int end = length - 1;
    while (currentNum <= end)
    {
        if (a[currentNum] == 2)
        {
            swap(a[end], a[currentNum]);
            end--;
        }
         else if (a[currentNum] == 1)
        {
            currentNum++;
        }
        else
        {
            if (begin == currentNum)
            {
                begin++;
                currentNum++;
            }
            else
            {
                swap(a[currentNum], a[begin]);
                begin++;
            }
        }
    }
}

int main()
{
    int a[] = { 1, 2, 0, 1, 2, 0, 1, 2, 1, 0, 2 };//原数组    
    int n = sizeof(a) / sizeof(int);//数组长度  
    for (int i = 0; i<n; i++)
        cout << a[i];   //输出原来的数组 
    cout << endl;
    Holland(a, n);
    for (int j = 0; j<n; j++)
        cout << a[j];
    cout << endl;
    getchar();
    return 0;
}

输出结果:

 

分类:

技术点:

相关文章: