Sort an array of 0s, 1s, and 2s without spaces

Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.

Examples:

Input: {0, 1, 2, 0, 1, 2} Output: {0, 0, 1, 1, 2, 2}

Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1} Output: {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2

Approach: The problem is similar to our old post Segregate 0s and 1s in an array, and both of these problems are variation of famous Dutch national flag problem. The problem was posed with three colours, here 0′,1′ and `2′. The array is divided into four sections:

  1. a[1..Lo-1] zeroes (red)
  2. a[Lo..Mid-1] ones (white)
  3. a[Mid..Hi] unknown
  4. a[Hi+1..N] ``` import java.io.*;

class sortArrays{

static void sort012(int a[], int arr_size) 
{ 
    int lo = 0; 
    int hi = arr_size - 1; 
    int mid = 0, temp = 0; 
    while (mid <= hi) { 
        switch (a[mid]) { 
        case 0: { 
            temp = a[lo]; 
            a[lo] = a[mid]; 
            a[mid] = temp; 
            lo++; 
            mid++; 
            break; 
        } 
        case 1: 
            mid++; 
            break; 
        case 2: { 
            temp = a[mid]; 
            a[mid] = a[hi]; 
            a[hi] = temp; 
            hi--; 
            break; 
        } 
        } 
    } 
} 

static void printArray(int arr[], int arr_size) 
{ 
    int i; 
    for (i = 0; i < arr_size; i++) 
        System.out.print(arr[i] + " "); 
    System.out.println(""); 
} 

public static void main(String[] args) 
{ 
    int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; 
    int arr_size = arr.length; 
    sort012(arr, arr_size); 
    System.out.println("Array after seggregation "); 
    printArray(arr, arr_size); 
} 

}

``` Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed. Space Complexity: O(1). No extra space is required.