# Sort an arrays of 0’s, 1’s and 2’s using Java

Given an array of 0, 1 and 2 sort the element in an order such that all the zeros come first before 1 and all the 2’s in the end. We have to sort all the elements of the array in-place.

We can solve this problem using DNF (Dutch National Flag) Sorting Algorithm. For example,

Input-1

arr[ ]= {2,0,0,1,2,1 }

Output

0 0 1 1 2 2

Explanation − Sorting the given array of elements containing 0,1 and 2 using the DNF Sorting Algorithm, it will print the output as {0,0,1,1,2,2}.

Input-2

arr[ ] = {0,1,1,2,1,1,0}

Output

0 0 1 1 1 1 2

Explanation − Sorting the given array of elements containing 0,1 and 2 using the DNF Sorting Algorithm, it will print the output as {0,0,1,1,1,1,2}.

## Approach to solve this problem

In the given array of 0, 1, and 2 we can use the DNF sorting algorithm.

DNF Sorting Algorithm − The algorithm requires 3 pointers to iterate throughout the array by swapping the necessary elements.

• Create a low pointer at the beginning of the array and a high pointer pointing at the end of the array.

• Find the Midpoint of the array and create a mid-pointer as well that iterates from the beginning of the array till the end.

• If the mid pointer of the array is ‘0’, then swap the element pointing at low. Increment the low pointer and mid pointer.

• If the mid-pointer of the array is ‘2’, then swap it with the element pointing at the high. Increment the mid pointer and decrement the high pointer.

• If the mid-pointer of the array is ‘1’, then increase the mid pointer.

## Example

Live Demo

public class Solution {
public static void binarySorting(int arr[], int n){
int low=0;
int high= n-1;
int mid=0;
while(mid<=high){
if(arr[mid]==0){
int temp= arr[mid];
arr[mid]= arr[low];
arr[low]= temp;
mid++;
low++;
}
if(arr[mid]==1){
mid++;
}
if(arr[mid]==2){
int temp= arr[mid];
arr[mid]= arr[high];
arr[high]= temp;
high--;
}
}
}
public static void print(int arr[], int n){
for (int i = 0; i < n; i++)
System.out.print(arr[i] +" ");
}
public static void main(String[] args){
int arr[] ={ 0,0,1,0,1,0,1,2,2};
int n = arr.length;
binarySorting(arr, n);
print(arr, n);
}
}

## Output

Running the above code will generate the output as,

0 0 0 0 1 1 1 1 2

Updated on: 05-Feb-2021

262 Views