我浏览了 Skiena 的书,也看到了这个问题,这是我的解决方案。
#include <stdio.h>
//swap the ith element of A with the jth element.
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; // counter
char p; // pivot element
int firsthing; // divider position for pivot
p = color; // choose the pivot element
firsthing = high; // divider position for pivot element
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);
}