面试题11

来源:互联网 发布:大学生搜题软件 编辑:程序博客网 时间:2024/05/05 21:22

三色球排序的问题:将相同的球放到一起,让你按顺序输出红白蓝三种颜色的球,可以用012来表示,要求只能扫描一次数组。

如:
输入 01012011022;
输出 00001111222;

思想:设定三个指针begin、current、end。初始化begin、current指向第一个,end指向最后一个。
current遍历整个序列,直到current>=end
(1)若current=1,不变;
(2)若current=0,交换begin,current++,begin++;
(3)若current=2,交换end,end–;

#include<stdio.h>#define N 10int main() {    int A[] = { 1,1,2,1,1,1,1,1,1,1 };    int begin, current, end,t;    for (begin = 0, current = 0, end = N - 1; current<end; current++) {        if (A[current] == 0) {            t = A[current];            A[current] = A[begin];            A[begin] = t;            begin++;            current++;        }        else if (A[current] == 1)            continue;        else if (A[current]== 2) {            t = A[current];            A[current] = A[end];            A[end] = t;            end--;        }    }    for (int i = 0; i < N; i++) {        printf("%d  ", A[i]);    }    return 0;}
0 0