Dutch National Flag (Java)

Question is from here:

A famous problem given by Edsgar Dijkstra is to sort an array of red, white and blue symbols so that all reds come together, followed by all whites, followed finally by all blues; it’s called the Dutch National Flag problem because the Dutch flag consists of three stripes with red at the top, blue at the bottom, and white in the middle. You are allowed to scan through the array only once, and the only operations permitted are to examine the color of the symbol at a given array location and to swap the symbols at two locations.

Your task is to write a program to perform the sort given above.

Solution:

import java.util.ArrayList;

public class Dutch_National_Flag {
	public static void main(String[] args) {
		//test cases
		String [] s = {"R","R","W","B","R","R","R"};
		String [] s1 = {"B", "W", "B", "R", "W", "R", "B"};
		flagIt(s);
		flagIt(s1);
	}
	
	private static void flagIt(String[] s) {
		int redIndex = 0, blueIndex = 0, whiteIndex = 0;
		//storing result 
		ArrayList<String> res = new ArrayList<String>();

		for (int i = 0; i < s.length; i++) {
			if(s[i].equals("R")) {
				res.add(redIndex, s[i]);
				redIndex++;
				blueIndex++;
				whiteIndex++;
			} else if (s[i].equals("W")) {
				res.add(whiteIndex, s[i]);
				whiteIndex++;
				blueIndex++;
			} else {
				res.add(blueIndex, s[i]);
				blueIndex++;
			}
		}
		System.out.println(res);
	}
}

Output:

[R, R, R, R, R, W, B]
[R, R, W, W, B, B, B]
About these ads

2 thoughts on “Dutch National Flag (Java)

  1. It is a working solution. But doesn’t using another array to hold the result defeat the purpose? Considering the fact that “the only operations permitted are to examine the color of the symbol at a given array location and to swap the symbols at two locations”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s