Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
Counting Sort Visualization using JavaScript
Next article icon

Sort an array of 0s, 1s and 2s (Simple Counting)

Last Updated : 17 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array A[] consisting of 0s, 1s, and 2s, write a function that sorts A[]. 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}

Count the number of 0’s, 1’s, and 2’s. After Counting, put all 0’s first, then 1’s and lastly 2’s in the array. We traverse the array two times.

C++




// Simple C++ program to sort an array of 0s 1s and 2s.
#include <iostream>
using namespace std;
 
void sort012(int* arr, int n)
{
    // Variables to maintain the count of 0's, 1's and 2's
    // in the array
    int count0 = 0, count1 = 0, count2 = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] == 0)
            count0++;
        if (arr[i] == 1)
            count1++;
        if (arr[i] == 2)
            count2++;
    }
 
    // Putting the 0's in the array in starting.
    for (int i = 0; i < count0; i++)
        arr[i] = 0;
 
    // Putting the 1's in the array after the 0's.
    for (int i = count0; i < (count0 + count1); i++)
        arr[i] = 1;
 
    // Putting the 2's in the array after the 1's
    for (int i = (count0 + count1); i < n; i++)
        arr[i] = 2;
 
    return;
}
 
// Prints the array
void printArray(int* arr, int n)
{
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
}
 
// Driver code
int main()
{
    int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    sort012(arr, n);
    printArray(arr, n);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)
 
 

C




// Simple C program to sort an array of 0s 1s and 2s.
#include <stdio.h>
 
void sort012(int* arr, int n)
{
    // Variables to maintain the count of 0's, 1's and 2's
    // in the array
    int count0 = 0, count1 = 0, count2 = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] == 0)
            count0++;
        if (arr[i] == 1)
            count1++;
        if (arr[i] == 2)
            count2++;
    }
 
    // Putting the 0's in the array in starting.
    for (int i = 0; i < count0; i++)
        arr[i] = 0;
 
    // Putting the 1's in the array after the 0's.
    for (int i = count0; i < (count0 + count1); i++)
        arr[i] = 1;
 
    // Putting the 2's in the array after the 1's
    for (int i = (count0 + count1); i < n; i++)
        arr[i] = 2;
 
    return;
}
 
// Prints the array
void printArray(int* arr, int n)
{
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}
 
// Driver code
int main()
{
    int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    sort012(arr, n);
    printArray(arr, n);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)
 
 

Java




// Simple Java program to sort an array of 0s 1s and 2s.
import java.lang.*;
import java.util.*;
 
public class GfG {
 
    public static void sort012(int arr[], int n)
    {
        // Variables to maintain the count of 0's, 1's and
        // 2's in the array
        int count0 = 0, count1 = 0;
        int count2 = 0;
        for (int i = 0; i < n; i++) {
            if (arr[i] == 0)
                count0++;
            if (arr[i] == 1)
                count1++;
            if (arr[i] == 2)
                count2++;
        }
 
        // Putting the 0's in the array in starting.
        for (int i = 0; i < count0; i++)
            arr[i] = 0;
 
        // Putting the 1's in the array after the 0's.
        for (int i = count0; i < (count0 + count1); i++)
            arr[i] = 1;
 
        // Putting the 2's in the array after the 1's
        for (int i = (count0 + count1); i < n; i++)
            arr[i] = 2;
 
        printArray(arr, n);
    }
 
    // Prints the array
    public static void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
        System.out.println();
    }
 
    // Driver function
    public static void main(String args[])
    {
 
        int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 };
        int n = 12;
        sort012(arr, n);
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)
 
 

Python3




# Python C++ program to sort an array of 0s
# 1s and 2s.
import math
 
def sort012(arr, n):
 
    # Variables to maintain the count of 0's,
    # 1's and 2's in the array
    count0 = 0
    count1 = 0
    count2 = 0
    for i in range(0,n):
        if (arr[i] == 0):
            count0=count0+1
        if (arr[i] == 1):
            count1=count1+1
        if (arr[i] == 2):
            count2=count2+1
     
 
    # Putting the 0's in the array in starting.
    for i in range(0,count0):
        arr[i] = 0
     
    # Putting the 1's in the array after the 0's.
    for i in range( count0, (count0 + count1)) :
        arr[i] = 1
     
    # Putting the 2's in the array after the 1's
    for i in range((count0 + count1),n) :
        arr[i] = 2
     
    return
 
 
# Prints the array
def printArray( arr,  n):
 
    for i in range(0,n):
        print( arr[i] , end=" ")
    print()
 
 
# Driver code
arr = [ 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ]
n = len(arr)
sort012(arr, n)
printArray(arr, n)
 
# This code is contributed by Gitanjali.
 
 

C#




// Simple C# program
// to sort an array of 0s
// 1s and 2s.
using System;
 
public class GfG{
 
    public static void sort012(int []arr, int n)
    {
        // Variables to maintain
        // the count of 0's,
        // 1's and 2's in the array
        int count0 = 0, count1 = 0;
        int count2 = 0;
        for (int i = 0; i < n; i++) {
            if (arr[i] == 0)
                count0++;
            if (arr[i] == 1)
                count1++;
            if (arr[i] == 2)
                count2++;
        }
     
        // Putting the 0's in the
        // array in starting.
        for (int i = 0; i < count0; i++)
            arr[i] = 0;
     
        // Putting the 1's in the
        // array after the 0's.
        for (int i = count0; i <
            (count0 + count1); i++)
            arr[i] = 1;
     
        // Putting the 2's in the
        // array after the 1's
        for (int i = (count0 + count1);
            i < n; i++)
            arr[i] = 2;
     
        printArray(arr, n);
    }
     
    // Prints the array
    public static void printArray(int []arr, int n)
    {
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
        Console.WriteLine();
    }
     
    // Driver function
    public static void Main()
    {
     
        int []arr = { 0, 1, 1, 0, 1, 2, 1,
                    2, 0, 0, 0, 1 };
        int n = 12;
        sort012(arr, n);
    }
}
 
// This code is contributed by vt_m
 
 

Javascript




<script>
 
// JavaScript program
// to sort an array of 0s
// 1s and 2s.
 
    function sort012(arr, n)
    {
        // Variables to maintain
        // the count of 0's,
        // 1's and 2's in the array
        let count0 = 0, count1 = 0;
        let count2 = 0;
        for (let i = 0; i < n; i++) {
            if (arr[i] == 0)
                count0++;
            if (arr[i] == 1)
                count1++;
            if (arr[i] == 2)
                count2++;
        }
      
        // Putting the 0's in the
        // array in starting.
        for (let i = 0; i < count0; i++)
            arr[i] = 0;
      
        // Putting the 1's in the
        // array after the 0's.
        for (let i = count0; i <
            (count0 + count1); i++)
            arr[i] = 1;
      
        // Putting the 2's in the
        // array after the 1's
        for (let i = (count0 + count1);
            i < n; i++)
            arr[i] = 2;
      
        printArray(arr, n);
    }
      
    // Prints the array
    function printArray(arr, n)
    {
        for (let i = 0; i < n; i++)
            document.write(arr[i] + " ");
        document.write();
    }
 
       
 
// Driver code
         
        let arr = [ 0, 1, 1, 0, 1, 2, 1,
                    2, 0, 0, 0, 1 ];
        let n = 12;
        sort012(arr, n);
         
</script>
 
 
Output
0 0 0 0 0 1 1 1 1 1 2 2  

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

Problems with the above solution.:

  1. It requires two traversals of array.
  2. This solution may not work if values are a part of the structure. For example, consider a situation where 0 represents Computer Science Stream, 1 represents Electronics and 2 represents Mechanical. We have a list of student objects (or structures) and we want to sort them. We cannot use the above sort as we simply put 0s, 1s, and 2s one by one.

Another Approach:

C++




// C++ program
#include <bits/stdc++.h>
using namespace std;
// Example
//
// input = [0, 1, 2, 2, 0, 0]
// output = [0, 0, 0, 1, 2, 2]
 
int main() {
     
    vector<int> inputArray={0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1};
    vector<int> outputArray;
    int indexOfOne = 0;
    for(int item: inputArray)
    {
        if(item==2)
        {   outputArray.push_back(item);
        }
        else if(item==1)
        {   outputArray.insert(outputArray.begin() + indexOfOne, item);
            indexOfOne+=1;
        }
        else if(item==0)
        {   outputArray.insert(outputArray.begin(), item);
            indexOfOne+=1;
        }
        else
        {   cout<<" wrong value - Aborting ";
            continue;
        }
    }
     
    for(int i=0;i<outputArray.size();i++)
    {
        cout<<outputArray[i]<<" ";
    }
 
    return 0;
}
// This code is contributed by Pushpesh Raj
 
 

Java




import java.util.ArrayList;
import java.util.List;
 
// Example
//
// input = [0, 1, 2, 2, 0, 0]
// output = [0, 0, 0, 1, 2, 2]
class GFG {
    static int[] inputArray = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 };
    static List<Integer> outputArray = new ArrayList<>();
    static int indexOfOne = 0;
 
    static void print() {
        for (int item : inputArray)
            if (item == 2)
                outputArray.add(item);
            else if (item == 1) {
                outputArray.add(indexOfOne, item);
                indexOfOne += 1;
            } else if (item == 0) {
                outputArray.add(0, item);
                indexOfOne += 1;
            } else {
                System.out.println(" wrong value - Aborting ");
                continue;
            }
    }
 
    public static void main(String[] args) {
        print();
        for (int item : outputArray)
            System.out.print(item+", ");
    }
}
// This code is contributed by Amit Katiyar
 
 

Python3




# Example
#
# input = [0, 1, 2, 2, 0, 0]
# output = [0, 0, 0, 1, 2, 2]
 
inputArray = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]
outputArray = []
indexOfOne = 0
for item in inputArray:
    if item == 2:
        outputArray.append(item)
    elif item == 1:
        outputArray.insert(indexOfOne, item)
        indexOfOne += 1
    elif item == 0:
        outputArray.insert(0, item)
        indexOfOne += 1
    else:
        print(" wrong value - Aborting ")
        continue
print(outputArray)
 
 

C#




using System;
using System.Collections.Generic;
 
// Example
//
// input = [0, 1, 2, 2, 0, 0]
// output = [0, 0, 0, 1, 2, 2]
 
class GFG{
     
static int[] inputArray = { 0, 1, 1, 0, 1, 2,
                            1, 2, 0, 0, 0, 1 };
static List<int> outputArray = new List<int>();
static int indexOfOne = 0;
 
static void print()
{
    foreach (int item in inputArray)
        if (item == 2)
            outputArray.Add(item);
        else if (item == 1)
        {
            outputArray.Insert(indexOfOne, item);
            indexOfOne += 1;
        }
        else if (item == 0)
        {
            outputArray.Insert(0, item);
            indexOfOne += 1;
        }
        else
        {
            Console.WriteLine(" wrong value - Aborting ");
            continue;
        }
}
 
// Driver code
public static void Main(String[] args)
{
    print();
    foreach(int item in outputArray)
        Console.Write(item + ", ");
}
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
 
// Example
//
// input = [0, 1, 2, 2, 0, 0]
// output = [0, 0, 0, 1, 2, 2]
let inputArray=[ 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ];
let outputArray = [];
let indexOfOne = 0;
 
function print()
{
    for (let item of inputArray.values())
            if (item == 2)
                outputArray.push(item);
            else if (item == 1) {
                outputArray.splice(indexOfOne,0, item);
                indexOfOne += 1;
            } else if (item == 0) {
                outputArray.splice(0,0, item);
                indexOfOne += 1;
            } else {
                document.write(" wrong value - Aborting ");
                continue;
            }
}
 
print();
for (let item of outputArray.values())
    document.write(item+", ");
 
// This code is contributed by rag2127
</script>
 
 
Output
0 0 0 0 0 1 1 1 1 1 2 2 

Time Complexity: O(n)
Auxiliary Space: O(n)

Optimal Solution that handles above issues : Sort an array of 0s, 1s and 2s (Dutch National Flag Algorithm)



Next Article
Counting Sort Visualization using JavaScript

A

Apoorva Balyan
Improve
Article Tags :
  • DSA
  • Sorting
  • counting-sort
  • limited-range-elements
Practice Tags :
  • Sorting

Similar Reads

  • Counting Sort - Data Structures and Algorithms Tutorials
    Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
    9 min read
  • Median and Mode using Counting Sort
    Given an n sized unsorted array, find median and mode using counting sort technique. This can be useful when array elements are in limited range. Examples: Input : array a[] = {1, 1, 1, 2, 7, 1} Output : Mode = 1 Median = 1 Note: Median is average of middle two numbers (1 and 1) Input : array a[] =
    12 min read
  • Implementing Counting Sort using map in C++
    Counting Sort is one of the best sorting algorithms which can sort in O(n) time complexity but the disadvantage with the counting sort is it's space complexity, for a small collection of values, it will also require a huge amount of unused space. So, we need two things to overcome this: A data struc
    2 min read
  • Counting Sort - Python
    Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
    7 min read
  • C Program for Counting Sort
    Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. Algorithm: Step 1: StartStep 2 : Find Larg
    3 min read
  • Java Program for Counting Sort
    Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. Java Code // Java implementation of Counti
    2 min read
  • Parallel Count Sort
    What is Parallel Count Sort?Parallel count sort is an efficient algorithm that sorts an array of elements in a parallel manner. It is a variation of the classic count sort algorithm which is used to sort a collection of objects based on their frequency. The algorithm is based on the idea of counting
    12 min read
  • Problem based on Counting Sort

    • Find duplicates in an Array with values 1 to N using counting sort
      Given a constant array of N elements which contain elements from 1 to N - 1, with any of these numbers appearing any number of times.Examples: Input: N = 5, arr[] = {1, 3, 4, 2, 2} Output: 2 Explanation: 2 is the number occurring more than once.Input: N = 5, arr[] = {3, 1, 3, 4, 2} Output: 3 Explana
      11 min read

    • Kth smallest or largest element in unsorted Array using Counting Sort
      Given an array arr[] and a number K, where K is smaller than the size of the array, we need to find the Kth smallest element in the given array. It is given that array elements can be repeated (not limited to distinct). Examples: Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7 Input: arr[] = {
      7 min read

    • Sort an array of 0s, 1s and 2s (Simple Counting)
      Given an array A[] consisting of 0s, 1s, and 2s, write a function that sorts A[]. 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,
      11 min read

  • Counting Sort Visualization using JavaScript
    GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Counting Sort using JavaScript. We will see how the frequencies of elements are stored and how we get the final sorted array. We will also visualize the time complexity of Counting Sort.
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences