×

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the inspiration for this flag, as its name suggests. To ensure that objects with the same color are grouped collectively, must distribute the red, white, and blue balls uniformly.

willThe will resolve mentioned issue through the use of an array. We shall arrange the arrays to match the hue of both the bolls. Rather than colors, we will utilize the numbers 0, 1, and 2, which stand in for the red, white, and blue hues.

Navie Methodology

Counting and sorting the arrays is a simple alternative. To sort these elements (0, 1, and 2), we tally how often they occur before placing them in the appropriate order. The method's drawback is that it scans the array twice: once to sort its components and again to arrange them properly.

To address the weakness above, we rearranged the arrangement to resolve the issue in a single traverse. The values are split into the three subgroups using an alternate linear-time division technique (also known as a 3-way division).

  • Values (in red) below the pivot point.
  • The center is equivalent to the numbers (white), and.
  • The (blue) results exceed the midpoint.

Algorithm

three-way-partitioning technique(Arr : array of values, mid : value):  
   l ← 0 
   m← 0  
   n ← size of Arr - 1  
   while m<= n:  
       if A[m] < mid:  
           swap Arr[l] and Arr[m]  
           l ← l + 1  
           m ← m+ 1  
       else if Arr[m] > mid:  
           swap Arr[m] and A[n]  
           n ← n- 1  
       else:  
           m ← m+ 1

Java Program for dutch national flag problem

Example: NationalFlagOfDutch

// this program is for the dutch national flag challenge
//importing the packages
import java.util.Arrays;  
public class NationalFlagOfDutch  
{  
    // A linear time partitioning procedure is used to sort an array with 
    //the values 0, 1, and 2. It is comparable to the 3-way dividing solution for the Dutch national flag issue.  
    public static void threeWayPartitions(int[] Arr)  
    {  
        int starts = 0, mids= 0;  
        int pivots = 1;  
        int ends = Arr.length - 1;  
        while (mids <= ends)  
        {  
            if (Arr[mids] < pivots)         // checks for the current position element  
            {  
                swaps(Arr, starts, mids);  
                ++starts;  
                ++mids;  
            }  
            else if (Arr[mids] > pivots)    //  check the current element is 2 or not  
            {  
                swaps(Arr, mids, ends);  
                --ends;  
            }  
            else {                      //  check the current element is 1
                ++mids;  
            }  
        }  
    }   
    //Convenience method to switch the arra's parts Arr[i] and Arr[j]  
    private static void swaps(int[] Arr, int i, int j)  
    {  
        int temps = Arr[i];  
        Arr[i] = Arr[j];  
        Arr[j] = temps;  
    }  
// the main section of the program
    public static void main (String args[])  
    {  
    // the array for sorting the elements 
        int[] Arr = { 0,2,0,2,0,0,1,1};  
   
        threeWayPartitions(Arr);  
    // displaying the sorted array
        System.out.println(Arrays.toString(Arr));  
    }  
}  

Output

[0, 0, 0, 0, 0, 1, 1, 2, 2]

Example2: DutchNationalFlagProblem.java

// this program is for the dutch national flag challenge
//importing the packages
import java.io.*;   
public class DutchNationalFlagProblem   
{   
    static void DNF(int array[], int arr_sizes)   
    {   
        int lows = 0;   
        int hig = arr_sizes - 1;   
        int mids = 0, temps=0; // For switching, temp variables are utilised.
        while (mids <= hig)   
        {   
            switch (array[mids])   
            {   
        case 0: // if indeed the midpointer is at 0,
        {   
        // logic for the swapping      
          temps = array[lows];   
          array[lows] = array[mids];   
          array[mids] = temps;   
          lows++;   
          mids++;   
          break;   
        }   
        case 1: 
            //If the midpoint is at 1, nothing switching is needed; increase your midpointer.
          mids++;   
          break;   
        case 2: // condition for mid pointer
        {   
        //logic for swapping   
          temps = array[mids];   
          array[mids] = array[hig];   
          array[hig] = temps;   
          hig--;   
          break;   
        }   
            }   
        }   
    }   
    // the method for displaying the sorted and unsorted array  
    static void printArray(int array[], int arr_sizes)   
    {   
        int i;   
        // loop for iterating the array  
        for (i = 0; i < arr_sizes; i++)   
        // displaying the elements
            System.out.print(array[i]+" ");   
            // the space is printed  
        System.out.println("");   
    }   
     // the main section of the program  
    public static void main (String args[])   
    {   
        int array[] = {0, 2, 1, 1, 0, 1, 2};   
        //identifies the element's length  
        int arr_sizes = array.length;   
    System.out.println(" The array before the sorting method: ");   
        printArray(array, arr_sizes);   
        // the method for calling before sorting
    DNF(array, arr_sizes);   
    // displaying the sorted array
    System.out.println(" The array after the sorting method: ");   
    // the function can be called after the sorting
        printArray(array, arr_sizes);   
    }   
}  

Output

 The array before the sorting  method: 
0 2 1 1 0 1 2 
 The array after the sorting method: 
0 0 1 1 1 2 2 

Related Topics

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java. Introduction Firstly, let us revise what is string Strings are collections of characters that are frequently used in...

4 minutes read.

StringBuilder in Java

StringBuilder in Java Java StringBuilder class is introduced since JDK 1.5. The StringBuilder class is mainly used to create modifiable or mutable strings. Note that the StringBuilder class is not synchronized....

7 minutes read.

Order of Execution of Constructors in Java Inheritance

Constructor in Java There are several distinctions between a method and a function object() in Java. The name of the function object()  is identical to the class name. There is no...

4 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

Java Open File

Java Desktop class give an open() strategy to open a filr. It has a place with a java.awt package. Work area execution is stage subordinate, so it is important to...

5 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1....

3 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively...

4 minutes read.

Java Boolean Class

The Boolean class wraps a value of the Boolean primitive in an object. Its object contains only a single field whose type is Boolean. Boolean Methods: This class contains several different methods...

2 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.