/** * flag.c * flag simple implementation of the Dutch National Flag algorithm * and some related things */ // +---------+------------------------------------------------------- // | Headers | // +---------+ #include "flag.h" #include // +------------------+---------------------------------------------- // | Local Procedures | // +------------------+ void swap (color flag[], int a, int b) { color tmp = flag[a]; flag[a] = flag[b]; flag[b] = tmp; } // +---------------------+------------------------------------------- // | Exported Procedures | // +---------------------+ void dnf (color flag[], int len) { int p3 = len; int p1 = 0; int p2 = 0; // R, W, B, p1 >= 0, p2 >= 0 while (p3 > p2) { // R, W, B, p1 >= 0, p2 >= 0, p3 > p2 // R, W, B, p1 >= 0, p2 >= 0, p3 > 0 if (WHITE == flag[p2]) { // R, B, flag[p1..p2) is white // R, B, flag[p1..p2+1) is white p2 += 1; // We've shrunk p3-p2 } else if (RED == flag[p2]) { // flag[0..p1) is red, flag[p1..p2) is white, B // Note: flag[p1] is white (or maybe not???) swap(flag,p1,p2); // flag[0..p1+1) is red, flag[p1+1..p2+1) is white p1 += 1; p2 += 1; // We've shrunk p3-p2; } else if (BLUE == flag[p2]) { swap(flag, p2, p3); // R, W, B // We haven't changed the size. Danger! } // Option 1: flag[p3-1] is blue. This is safe. if (BLUE == flag[p3-1]) { // R, W, flag[p3..n) is blue // R, W, flag[p3-1..n) is blue p3 -= 1; // R, W, B // We've shrunk p3-p2 } } // } // dnf void printflag (color flag[], int len) { for (int i = 0; i < len; i++) { switch (flag[i]) { case RED: printf ("R"); break; case WHITE: printf ("W"); break; case BLUE: printf ("B"); break; default: printf ("?"); break; } // switch } // for printf ("\n"); } // printflag