直接贴代码吧,也不知道当时是怎么想出来的,一下就想到这么做了
- redc = 0;
- whitec = N - 1;
- for (i=0; i<=whitec;)
- {
- if (pot[i] == 1)//当颜色为红色时,与前面的元素交换,然后判断下一位
- {
- if (i > redc)
- {
- temp = pot[i];
- pot[i] = pot[redc];
- pot[redc] = temp;
- }
- redc++;
- i++;
- }
- if (pot[i] == 2)//当颜色为蓝色时,不变,判断下一位
- {
- i++;
- continue;
- }
- if (pot[i] == 3)//当颜色为白色时,与后面的元素交换,仍然判断第i个元素
- {
- if (whitec > i)
- {
- temp = pot[i];
- pot[i] = pot[whitec];
- pot[whitec] = temp;
- }
- whitec--;
- }
- }