题目描述:
现有n个红白蓝三种不同颜色的小球,,乱序排序在一起,请通过两两交换任意两个球,使得从左至右的球依次是红(1),白(1),蓝(2)。
基本思路:
划分过程:一个前指针begin,一个中指针current,一个后指针end,current指针遍历整个数组序列
(1)当current指针指向0时,与begin指针指向的内容交换,而后current++,begin++;
(2)当current指针指向1时,不做任何交换,而后current++;
(3)当current指针指向2时,与end指针指向的元素交换,而后end--;
current不动
c代码如下:
-
#include<stdio.h>
-
#include<stdlib.h>
-
#include<string.h>
-
#define swap(t,x,y) (t = (x),x = (y),y = (t))//最近总写错swap宏定义
-
void sort(int *a,int lo,int hi)
-
{
-
int begin = lo;
-
int end = hi;
-
int current = lo;
-
int temp = 0;
-
while (current <= end)
-
{
-
if (a[current] == 0)
-
{
-
swap(temp,a[current],a[begin]);
-
current++;
-
begin++;
-
}
-
else if (a[current] == 1)
-
{
-
current++;
-
}
-
else
-
{
-
swap(temp,a[current],a[end]);
-
end--;//这个忘写了 2016.8.20
-
}
-
}
-
}
-
int main()
-
{
-
int len = 0;
-
printf("请输入数组长度:");
-
scanf("%d",&len);
-
int a[len];
-
memset(a,0,len);
-
int i = 0;
-
for (i = 0;i < len;i++)
-
{
-
printf("请输入第%d个元素",i+1);
-
scanf("%d",&a[i]);
-
}
-
sort(a,0,len-1);
-
for (i = 0;i < len;i++)
-
{
-
printf("%d ",a[i]);
-
}
-
printf("\n");
-
return 0;
-
}
运行结果如下:(centos5.5)
[root@localhost ~]# ./a.out
请输入数组长度:3
请输入第1个元素1
请输入第2个元素0
请输入第3个元素2
0 1 2
阅读(815) | 评论(0) | 转发(0) |