Fork me on GitHub

P_52荷兰国旗

何谓荷兰国旗:

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

 

问题转换为:给定数组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 <iostream>
#define N 100
using namespace std;

void sortColors(int A[],int n)
{
	if(n<1)
	{
		return;
	}
	int begin=0,current=0,end=n-1;
	while(current<=end)
	{
		//当中间指针指向0时,与begin元素交换,current++,begin++; 
		if(A[current]==0)
		{
			swap(A[current],A[begin]);
			current++;
			begin++; 
		}
		//当current指向1时,current++; 
		else if(A[current]==1)
		{
			current++;
		 } 
		//当current指向2时,与end元素交换,end-- ; 
		else //(A[current] ==2)
		{
			swap(A[current],A[end]);
			end--;
		}
	}
}

int main()
{
	void sortColors(int A[],int n);
	int a[]={2,0,1,0,0,2,1,1,2};
	int n=sizeof(a)/sizeof(int);
	for(int i=0;i<n;i++)
	{
		cout<<a[i];
	}
	cout<<endl;
	sortColors(a,n);
	for(int i=0;i<n;i++)
	{
		cout<<a[i];
	}
	return 0;
 } 

  

 

posted @ 2018-05-10 17:38  风中等待  阅读(202)  评论(0编辑  收藏  举报