我已经阅读了Skiena的书,并看到了这个问题,这是我的解决方案。
#include <stdio.h>
void swap(char arr[], int i, int j) {
char temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return;
}
int partition_color(char arr[], int low, int high, char color)
{
int i;
char p;
int firsthing;
p = color;
firsthing = high;
for (i = low; i < firsthing; i++) {
if (arr[i] == color) {
swap(arr, i, firsthing);
firsthing--;
}
}
return(firsthing);
}
void red_white_blue_sorting(char arr[], int n) {
int pos;
pos = partition_color(arr, 0, n, 'b');
partition_color(arr, 0, pos, 'w');
return;
}
int main() {
char arr[] = {'r', 'b', 'r', 'w', 'b', 'w', 'b', 'r', 'r'};
int n = sizeof(arr) / sizeof(arr[0]);
red_white_blue_sorting(arr, n);
for (int i = 0; i < n; i++)
printf("%c ", arr[i]);
printf("\n");
return(0);
}