Skip to content
Related Articles

Related Articles

Improve Article
Sort an array of 0s, 1s, 2s and 3s
  • Difficulty Level : Medium
  • Last Updated : 01 Jun, 2021

Given an array arr[] of size N consisting of 0, 1, 2, and 3 only, the task is to sort the given array in ascending order.

Example: 

Input: arr[] = {0, 3, 1, 2, 0, 3, 1, 2}
Output: 0 0 1 1 2 2 3 3

Input: arr[] = {0, 1, 3, 1, 0, 1, 3, 2, 1, 2, 0, 3, 0, 0, 1}
Output: 0 0 0 0 0 1 1 1 1 1 2 2 3 3 3

 

Approach: The given problem can be solved based on the approach discussed in this article. The idea is first to position all the 0s and 3s at the beginning and end of the array, followed by sorting the occurrences of integers 1 and 2



Follow the steps below to solve the problem:

  • Initialize three variables, say i, mid, and j. Set the values of i and mid as 0 and j as (N – 1).
  • Iterate a loop until mid ≤ j and perform the following steps:
    • If the value of arr[mid] is 0, then swap arr[i] and arr[mid] and increment the value of i and mid by 1.
    • Otherwise, if the value of arr[mid] is 3, then swap arr[mid] and arr[j] and decrement j by 1.
    • Otherwise, if the value of arr[i] is either 1 or 2, then increment the value of mid by 1.
  • Now to sort the subarray over the range [i, j] by iterating until i ≤ j and perform the following operations:
    • If the value of arr[i] is 2, then swap arr[i] and arr[j] and decrement the value of j by 1.
    • Otherwise, increment the value of i by 1.
  • After completing the above steps, print the array arr[] as the resultant sorted array.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to sort the array having
// array element only 0, 1, 2, and 3
void sortArray(int arr[], int N)
{
    int i = 0, j = N - 1, mid = 0;
 
    // Iterate until mid <= j
    while (mid <= j) {
 
        // If arr[mid] is 0
        if (arr[mid] == 0) {
 
            // Swap integers at
            // indices i and mid
            swap(arr[i], arr[mid]);
 
            // Increment i
            i++;
 
            // Increment mid
            mid++;
        }
 
        // Otherwise if the value of
        // arr[mid] is 3
        else if (arr[mid] == 3) {
 
            // Swap arr[mid] and arr[j]
            swap(arr[mid], arr[j]);
 
            // Decrement j
            j--;
        }
 
        // Otherwise if the value of
        // arr[mid] is either 1 or 2
        else if (arr[mid] == 1
                 || arr[mid] == 2) {
 
            // Increment the value of mid
            mid++;
        }
    }
 
    // Iterate until i <= j
    while (i <= j) {
 
        // If arr[i] the value of is 2
        if (arr[i] == 2) {
 
            // Swap arr[i] and arr[j]
            swap(arr[i], arr[j]);
 
            // Decrement j
            j--;
        }
 
        // Otherwise, increment i
        else {
            i++;
        }
    }
 
    // Print the sorted array arr[]
    for (int i = 0; i < N; i++) {
        cout << arr[i] << " ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 2, 1, 0, 2, 3, 1, 0 };
    int N = sizeof(arr) / sizeof(arr[0]);
    sortArray(arr, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to sort the array having
// array element only 0, 1, 2, and 3
static void sortArray(int[] arr, int N)
{
    int i = 0, j = N - 1, mid = 0;
 
    // Iterate until mid <= j
    while (mid <= j)
    {
         
        // If arr[mid] is 0
        if (arr[mid] == 0)
        {
             
            // Swap integers at
            // indices i and mid
            int temp = arr[i];
            arr[i] = arr[mid];
            arr[mid] = temp;
 
            // Increment i
            i++;
 
            // Increment mid
            mid++;
        }
 
        // Otherwise if the value of
        // arr[mid] is 3
        else if (arr[mid] == 3)
        {
             
            // Swap arr[mid] and arr[j]
            int temp = arr[mid];
            arr[mid] = arr[j];
            arr[j] = temp;
 
            // Decrement j
            j--;
        }
 
        // Otherwise if the value of
        // arr[mid] is either 1 or 2
        else if (arr[mid] == 1 || arr[mid] == 2)
        {
             
            // Increment the value of mid
            mid++;
        }
    }
 
    // Iterate until i <= j
    while (i <= j)
    {
         
        // If arr[i] the value of is 2
        if (arr[i] == 2)
        {
             
            // Swap arr[i] and arr[j]
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
 
            // Decrement j
            j--;
        }
 
        // Otherwise, increment i
        else
        {
            i++;
        }
    }
 
    // Print the sorted array arr[]
    for(int k = 0; k < N; k++)
    {
        System.out.print(arr[k] + " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 3, 2, 1, 0, 2, 3, 1, 0 };
    int N = arr.length;
     
    sortArray(arr, N);
}
}
 
// This code is contributed by susmitakundugoaldanga

Python3




# Python3 program for the above approach
 
# Function to sort the array having
# array element only 0, 1, 2, and 3
def sortArray(arr, N):
    i = 0
    j = N - 1
    mid = 0
 
    # Iterate until mid <= j
    while (mid <= j):
 
        # If arr[mid] is 0
        if (arr[mid] == 0):
 
            # Swap integers at
            # indices i and mid
            arr[i], arr[mid] = arr[mid], arr[i]
 
            # Increment i
            i += 1
             
            # Increment mid
            mid += 1
 
        # Otherwise if the value of
        # arr[mid] is 3
        elif (arr[mid] == 3):
 
            # Swap arr[mid] and arr[j]
            arr[mid], arr[j] = arr[j], arr[mid]
             
            # Decrement j
            j -= 1
 
        # Otherwise if the value of
        # arr[mid] is either 1 or 2
        elif (arr[mid] == 1 or arr[mid] == 2):
            # Increment the value of mid
            mid += 1
 
    # Iterate until i <= j
    while (i <= j):
       
        # If arr[i] the value of is 2
        if (arr[i] == 2):
           
            # Swap arr[i] and arr[j]
            arr[i], arr[j] = arr[j], arr[i]
             
            # Decrement j
            j -= 1
 
        # Otherwise, increment i
        else:
            i += 1
 
    # Print the sorted array arr[]
    for i in range(N):
        print(arr[i], end = " ")
 
# Driver Code
if __name__ == '__main__':
    arr = [3, 2, 1, 0, 2, 3, 1, 0]
    N = len(arr)
    sortArray(arr, N)
 
#  This code is contributed by mohit kumar 29.

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to sort the array having
// array element only 0, 1, 2, and 3
static void sortArray(int[] arr, int N)
{
    int i = 0, j = N - 1, mid = 0;
 
    // Iterate until mid <= j
    while (mid <= j)
    {
         
        // If arr[mid] is 0
        if (arr[mid] == 0)
        {
             
            // Swap integers at
            // indices i and mid
            int temp = arr[i];
            arr[i] = arr[mid];
            arr[mid] = temp;
 
            // Increment i
            i++;
 
            // Increment mid
            mid++;
        }
 
        // Otherwise if the value of
        // arr[mid] is 3
        else if (arr[mid] == 3)
        {
             
            // Swap arr[mid] and arr[j]
            int temp = arr[mid];
            arr[mid] = arr[j];
            arr[j] = temp;
 
            // Decrement j
            j--;
        }
 
        // Otherwise if the value of
        // arr[mid] is either 1 or 2
        else if (arr[mid] == 1 || arr[mid] == 2)
        {
             
            // Increment the value of mid
            mid++;
        }
    }
 
    // Iterate until i <= j
    while (i <= j)
    {
         
        // If arr[i] the value of is 2
        if (arr[i] == 2)
        {
             
            // Swap arr[i] and arr[j]
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
 
            // Decrement j
            j--;
        }
 
        // Otherwise, increment i
        else
        {
            i++;
        }
    }
 
    // Print the sorted array arr[]
    for(int k = 0; k < N; k++)
    {
        Console.Write(arr[k] + " ");
    }
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 3, 2, 1, 0, 2, 3, 1, 0 };
    int N = arr.Length;
     
    sortArray(arr, N);
}
}
 
// This code is contributed by ukasp

Javascript




<script>
 
// javascript program for the above approach
 
// Function to sort the array having
// array element only 0, 1, 2, and 3
function sortArray(arr, N)
{
    var i = 0, j = N - 1, mid = 0;
 
    // Iterate until mid <= j
    while (mid <= j) {
 
        // If arr[mid] is 0
        if (arr[mid] == 0) {
 
            // Swap integers at
            // indices i and mid
            var temp = arr[i];
            arr[i] = arr[mid];
            arr[mid] = temp;
 
            // Increment i
            i++;
 
            // Increment mid
            mid++;
        }
 
        // Otherwise if the value of
        // arr[mid] is 3
        else if (arr[mid] == 3) {
             
            var temp = arr[mid];
            arr[mid] = arr[j];
            arr[j] = temp;
 
            // Decrement j
            j--;
        }
 
        // Otherwise if the value of
        // arr[mid] is either 1 or 2
        else if (arr[mid] == 1
                 || arr[mid] == 2) {
 
            // Increment the value of mid
            mid++;
        }
    }
 
    // Iterate until i <= j
    while (i <= j) {
 
        // If arr[i] the value of is 2
        if (arr[i] == 2) {
 
            // Swap arr[i] and arr[j]
            var temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
 
            // Decrement j
            j--;
        }
 
        // Otherwise, increment i
        else {
            i++;
        }
    }
 
    // Print the sorted array arr[]
    for (i = 0; i < N; i++) {
        document.write(arr[i] + " ");
    }
}
 
// Driver Code
    var arr = [3, 2, 1, 0, 2, 3, 1, 0];
    var N = arr.length;
    sortArray(arr, N);
     
</script>
Output: 
0 0 1 1 2 2 3 3

 

Time Complexity: O(N)
Auxiliary Space: O(1)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live 




My Personal Notes arrow_drop_up
Recommended Articles
Page :