Algorithms_ThreeColorFlag

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

void swap(int a,int b,char *l);
void sort(char *l);

void main()
{
	char ColorLine[]={'r','w','b','b','w','r','b','b','\0'};
	char *c;

	printf("The orginal order:\n");
	for (c=ColorLine;*c!='\0';c++)
	{
		printf("%c ",*c);
	}
	printf("\n");
	sort(ColorLine);
	printf("The ordered order:\n");
	for (c=ColorLine;*c!='\0';c++)
	{
		printf("%c ",*c);
	}
}

void swap(int a,int b,char *l)
{
	char t;
	t=l[a];
	l[a]=l[b];
	l[b]=t;
}
void sort(char *l)
{
	int wFlag=0;
	int bFlag=0;
	int rFlag=strlen(l)-1;
	while (wFlag<=rFlag)
	{
		if (l[wFlag]=='w')
		{
			wFlag++;
		}
		else if (l[wFlag]=='b')
		{
			swap(bFlag,wFlag,l);
			bFlag++;
			wFlag++;
		}
		else
		{
			while(wFlag < rFlag && l[rFlag]=='r')
				rFlag--;
			swap(wFlag,rFlag,l);
			rFlag--;
		}
	}
}

你可能感兴趣的:(algorithms)