Created
October 15, 2016 20:47
-
-
Save MaksimDmitriev/868851c9232e5f1aa54cc88e1a4d9cdf to your computer and use it in GitHub Desktop.
russianFlagProblem
This file contains 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
public static void russianFlagProblem(int[] input, int red, int white, int blue) { | |
// input: 1, 2, 3, 1, 1, 2, 3, 1, 1 | |
// Dutch: 1, 1, 1, 1, 1, 2, 2, 3, 3 | |
// (1 - red, 2 - white, 3 - blue) | |
// Russian: 2 - white, 3 - blue, 1 - red | |
// output: 2, 2, 3, 3, 1, 1, 1, 1, 1 | |
int i = 0; // the end of the white region (exclusive) | |
int j = 0; // the current element | |
int k = input.length - 1; // the start of the blue region (exclusive) | |
while (j <= k) { | |
if (input[j] == white) { | |
Utils.swap(input, j++, i++); | |
} else if (input[j] == red) { | |
Utils.swap(input, j, k--); | |
} else { | |
j++; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment