×

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

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Tilt operator in Java | Tilde operator in Java Example

The symbol designates it as a unary operator (pronounced as the tilde). It gives back the bit's complement or inverse. Every 0 turns into a 1, and every 1 back...

3 minutes read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.

Longest Odd Even Subsequence in Java

In order to solve the Java problem known as the longest odd-even subsequence, one must identify a sequences in a non-negative array having size s that alternately includes odd and...

6 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

Java String

Definition A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you...

4 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The...

6 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Java Math tan() Method

The tan() method of Java Math class returns the trigonometric tangent of the specified angle. Syntax: public static double tan(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The tan() method...

2 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.