Created
October 18, 2020 14:18
-
-
Save RobertDurfee/720122d7f57d058529c44c96f86f6767 to your computer and use it in GitHub Desktop.
A five-color, in-place partitioning algorithm in O(n)-time (based on the Dutch flag algorithm).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum Color { | |
ORANGE, | |
WHITE, | |
RED, | |
YELLOW, | |
GREEN, | |
}; | |
void swap(enum Color *a, enum Color *b) { | |
enum Color temp; | |
temp = *a; | |
*a = *b; | |
*b = temp; | |
} | |
// https://stackoverflow.com/a/43015749 | |
void jodhpur(enum Color *colors, int count) { | |
int orange = 0; | |
int white = 0; | |
int red = 0; | |
int yellow = 0; | |
int green = count - 1; | |
while (yellow <= green) { | |
switch (colors[yellow]) { | |
case ORANGE: | |
swap(&colors[orange], &colors[yellow]); | |
orange++; | |
if (white < orange) { | |
white++; | |
} | |
if (red < orange) { | |
red++; | |
} | |
if (yellow < orange) { | |
yellow++; | |
} | |
break; | |
case WHITE: | |
swap(&colors[white], &colors[yellow]); | |
white++; | |
if (red < white) { | |
red++; | |
} | |
if (yellow < white) { | |
yellow++; | |
} | |
break; | |
case RED: | |
swap(&colors[red], &colors[yellow]); | |
red++; | |
yellow++; | |
break; | |
case YELLOW: | |
yellow++; | |
break; | |
case GREEN: | |
swap(&colors[green], &colors[yellow]); | |
green--; | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment