// FlagArrange.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include
/*
由红白蓝三种颜色的球组成的序列,编写算法,使得该序列排列次序为红球,白球,蓝球,且时间复杂度为O(n);
思路:假设红白蓝三种颜色依次用数字1,2,3来表示,则问题变为:12223311123122221111113333,将这些随机序列变为111111122222333
*/
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
return;
}
int len(int list[])
{
int length = 0;
while(list[length] != 0)
length++;
return length;
}
void display(int list[])
{
printf("List: ");
for(int i = 0; i < len(list); i++)
{
printf("%d",list[i]);
}
printf("\n\n");
return;
}
void arrange(int list[])
{
int i = 0; //list[i]之前为1
int j = 0; //list[j]为当前需要处理的颜色
int k = len(list) -1; //list[k]之后的为3
while(j <= k)
{
switch(list[j])
{
case 1:
swap(list[i],list[j]);
i++;
j++;
break;
case 2:
j++;
break;
case 3:
swap(list[k],list[j]);
k--;
break;
}
}
return;
}
int _tmain(int argc, _TCHAR* argv[])
{
int list[] = {1,2,3,1,2,1,2,3,1,1,1,2,2,2,2,1,1,3,3,2,1,0};
display(list);
arrange(list);
display(list);
getchar();
return 0;
}
荷兰国旗问题
最新推荐文章于 2022-04-20 09:44:15 发布