问题:重新排列一个由Red、White和Blue(这是荷兰国旗的颜色)构成的数组,是的所有的Red都排在最前面,White排在其次,Blue排在最后面
#include <stdio.h>
#define N 8
enum Color{Red, White, Blue};
void Sort(enum Color a[],int n);
void PrintOut(enum Color a[],int n);
int main(){
enum Color a[N] = {White,Red,Red,Blue,White,Blue,Red,White};
Sort(a,N);
printf("排序后的序列为:");
PrintOut(a,N);
return 0;
}
void Sort(enum Color a[],int n){
int i = 0 , k = n - 1, j = 0;
enum Color temp;
while (j<=k)
switch (a[j]){
case Red: temp = a[i]; a[i] = a[j]; a[j] = temp; i++; j++; break;
case Blue: temp = a[j]; a[j] = a[k]; a[k] = temp; k--; break;
case White: j++; break;
}
}
void PrintOut(enum Color a[],int n){
int i;
for(i = 0 ; i < n ; i++)
switch (a[i]){
case Red: printf("Red "); break;
case White: printf("White "); break;
case Blue: printf("Blue "); break;
}
}
运行结果: