Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Sort an array of 0s, 1s and 2s - Dutch National Flag Problem
Next article icon

Sort an array of 0s, 1s and 2s - Dutch National Flag Problem

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array arr[] consisting of only 0s, 1s, and 2s. The task is to sort the array, i.e., put all 0s first, then all 1s and all 2s in last.

This problem is the same as the famous "Dutch National Flag problem". The problem was proposed by Edsger Dijkstra. The problem is as follows:

Given n balls of colour red, white or blue arranged in a line in random order. You have to arrange all the balls such that the balls with the same colours are adjacent with the order of the balls, with the order of the colours being red, white and blue (i.e., all red coloured balls come first then the white coloured balls and then the blue coloured balls). 

Examples:

Input: arr[] = {0, 1, 2, 0, 1, 2}
Output: {0, 0, 1, 1, 2, 2}
Explanation: {0, 0, 1, 1, 2, 2} has all 0s first, then all 1s and all 2s in last.

Input: arr[] = {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}
Explanation: {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2} has all 0s first, then all 1s and all 2s in last.

Table of Content

  • [Naive Approach] Sorting - O(n * log(n)) Time and O(1) Space
  • [Better Approach] Counting 0s, 1s and 2s - Two Pass - O(n) Time and O(1) Space
  • [Expected Approach] Dutch National Flag Algorithm - One Pass - O(n) Time and O(1) Space

[Naive Approach] Sorting - O(n * log(n)) Time and O(1) Space

The naive solution is to simply sort the array using a standard sorting algorithm or sort library function. This will simply place all the 0s first, then all 1s and 2s at last. This approach requires O(n * log(n)) time and O(1) space.

[Better Approach] Counting 0s, 1s and 2s - Two Pass - O(n) Time and O(1) Space

A better solution is to traverse the array once and count number of 0s, 1s and 2s, say c0, c1 and c2 respectively. Now traverse the array again, put c0 (count of 0s) 0s first, then c1 1s and finally c2 2s. This solution works in O(n) time, but it is not stable and requires two traversals of the array.

C++
// C++ Program to sort an array of 0s, 1s and 2s // by counting the occurrence of 0s, 1s and 2s  #include <iostream> #include <vector> using namespace std;  // Function to sort the array of 0s, 1s and 2s void sort012(vector<int> &arr) {     int n = arr.size();     int c0 = 0, c1 = 0, c2 = 0;      // Count 0s, 1s and 2s     for (int i = 0; i < n; i++) {         if (arr[i] == 0)             c0 += 1;         else if (arr[i] == 1)             c1 += 1;         else             c2 += 1;     }      int idx = 0;          // Place all the 0s     for (int i = 0; i < c0; i++)         arr[idx++] = 0;      // Place all the 1s     for (int i = 0; i < c1; i++)         arr[idx++] = 1;      // Place all the 2s     for (int i = 0; i < c2; i++)         arr[idx++] = 2; }  int main() {     vector<int> arr = { 0, 1, 2, 0, 1, 2 };     sort012(arr);      for (int i = 0; i < arr.size(); i++)         cout << arr[i] << " ";     return 0; } 
C
// C Program to sort an array of 0s, 1s and 2s // by counting the occurrence of 0s, 1s and 2s  #include <stdio.h>  // Function to sort the array of 0s, 1s and 2s void sort012(int arr[], int n) {     int c0 = 0, c1 = 0, c2 = 0;      // Count 0s, 1s and 2s     for (int i = 0; i < n; i++) {         if (arr[i] == 0)             c0 += 1;         else if (arr[i] == 1)             c1 += 1;         else             c2 += 1;     }      int idx = 0;          // Place all the 0s     for (int i = 0; i < c0; i++)         arr[idx++] = 0;      // Place all the 1s     for (int i = 0; i < c1; i++)         arr[idx++] = 1;      // Place all the 2s     for (int i = 0; i < c2; i++)         arr[idx++] = 2; }  int main() {     int arr[] = { 0, 1, 2, 0, 1, 2 };     int n = sizeof(arr) / sizeof(arr[0]);      sort012(arr, n);      for (int i = 0; i < n; i++)         printf("%d ", arr[i]);      return 0; } 
Java
// Java Program to sort an array of 0s, 1s and 2s // by counting the occurrence of 0s, 1s and 2s  class GfG {        // Function to sort the array of 0s, 1s and 2s     static void sort012(int[] arr) {         int n = arr.length;         int c0 = 0, c1 = 0, c2 = 0;          // Count 0s, 1s and 2s         for (int i = 0; i < n; i++) {             if (arr[i] == 0)                  c0 += 1;             else if (arr[i] == 1)                  c1 += 1;             else                  c2 += 1;         }          int idx = 0;                // Place all the 0s         for (int i = 0; i < c0; i++)             arr[idx++] = 0;          // Place all the 1s         for (int i = 0; i < c1; i++)             arr[idx++] = 1;          // Place all the 2s         for (int i = 0; i < c2; i++)             arr[idx++] = 2;     }        public static void main(String[] args) {         int[] a = { 0, 1, 2, 0, 1, 2 };         int n = a.length;          sort012(a);          for (int i = 0; i < n; i++)             System.out.print(a[i] + " ");     } } 
Python
# Python Program to sort an array of 0s, 1s and 2s # by counting the occurrence of 0s, 1s and 2s  # Function to sort an array of 0s, 1s and 2s def sort012(arr):     c0 = 0     c1 = 0     c2 = 0      # Count 0s, 1s and 2s     for num in arr:         if num == 0:             c0 += 1         elif num == 1:             c1 += 1         else:             c2 += 1      idx = 0          # Place all the 0s     for i in range(c0):         arr[idx] = 0         idx += 1      # Place all the 1s     for i in range(c1):         arr[idx] = 1         idx += 1      # Place all the 2s     for i in range(c2):         arr[idx] = 2         idx += 1   arr = [0, 1, 2, 0, 1, 2] sort012(arr)  for x in arr:   print(x, end = " ") 
C#
// C# Program to sort an array of 0s, 1s and 2s // by counting the occurrence of 0s, 1s and 2s  using System;  class GfG {        // Function to sort the array of 0s, 1s and 2s     static void sort012(int[] arr) {         int c0 = 0, c1 = 0, c2 = 0; 		         // Count 0s, 1s and 2s         for (int i = 0; i < arr.Length; i++) {             if (arr[i] == 0)                  c0 += 1;             else if (arr[i] == 1)                  c1 += 1;             else                  c2 += 1;         }          int idx = 0;                // Place all the 0s         for (int i = 0; i < c0; i++)             arr[idx++] = 0;          // Place all the 1s         for (int i = 0; i < c1; i++)             arr[idx++] = 1;          // Place all the 2s         for (int i = 0; i < c2; i++)             arr[idx++] = 2;     }      static void Main() {         int[] arr = { 0, 1, 2, 0, 1, 2 };         sort012(arr);          foreach(int num in arr)             Console.Write(num + " ");     } } 
JavaScript
// JavaScript Program to sort an array of 0s, 1s and 2s // by counting the occurrence of 0s, 1s and 2s  // Function to sort an array of 0s, 1s and 2s function sort012(arr) {     let c0 = 0, c1 = 0, c2 = 0;      // Count 0s, 1s, and 2s     for (let i = 0; i < arr.length; i++) {         if (arr[i] === 0)              c0 += 1;         else if (arr[i] === 1)              c1 += 1;         else             c2 += 1;     }      let idx = 0;     // Place all the 0s     for (let i = 0; i < c0; i++)          arr[idx++] = 0;      // Place all the 1s     for (let i = 0; i < c1; i++)          arr[idx++] = 1;      // Place all the 2s     for (let i = 0; i < c2; i++)          arr[idx++] = 2; }  let arr = [0, 1, 2, 0, 1, 2]; sort012(arr);  console.log(arr.join(' ')); 

Output
0 0 1 1 2 2 

Time Complexity: O(2 * n), where n is the number of elements in the array
Auxiliary Space: O(1)

The issues with this approach are:

  1. It would not work if 0s and 1s represent keys of objects.
  2. Not stable
  3. Requires two traversals

[Expected Approach] Dutch National Flag Algorithm - One Pass - O(n) Time and O(1) Space

The problem is similar to "Segregate 0s and 1s in an array". The idea is to sort the array of size n using three pointers: lo = 0, mid = 0 and hi = n - 1 such that the array is divided into three parts -

  • arr[0] to arr[lo - 1]: This part will have all the zeros.
  • arr[lo] to arr[mid - 1]: This part will have all the ones.
  • arr[hi + 1] to arr[n - 1]: This part will have all the twos.

Here, lo indicates the position where next 0 should be placed, mid is used to traverse through the array and hi indicates the position where next 2 should be placed.

Traverse over the array till mid <= hi, according to the value of arr[mid] we can have three cases:

  • arr[mid] = 0, then swap arr[lo] and arr[mid] and increment lo by 1 because all the zeros are till index lo - 1 and move to the next element so increment mid by 1.
  • arr[mid] = 1, then move to the next element so increment mid by 1.
  • arr[mid] = 2, then swap arr[mid] and arr[hi] and decrement hi by 1 because all the twos are from index hi + 1 to n - 1. Now, we don't move to the next element because the element which is now at index mid can be a 0 and therefore needs to be checked again.

Working:


C++
// C++ program to sort an array of 0s, 1s and 2s  // using Dutch National Flag Algorithm  #include <iostream> #include <vector> using namespace std;  // Function to sort an array of 0s, 1s and 2s void sort012(vector<int> &arr) {     int n = arr.size();     int lo = 0;     int hi = n - 1;     int mid = 0;      // Iterate till all the elements     // are sorted     while (mid <= hi) {         if (arr[mid] == 0)             swap(arr[lo++], arr[mid++]);         else if (arr[mid] == 1)             mid++;         else             swap(arr[mid], arr[hi--]);     } }  int main() {     vector<int> arr = { 0, 1, 2, 0, 1, 2 };     int n = arr.size();      sort012(arr);      for (int i = 0; i < n; i++)         cout << arr[i] << " ";      return 0; } 
C
// C program to sort an array of 0s, 1s and 2s  // using Dutch National Flag Algorithm  #include <stdio.h>  void swap(int *a, int *b) {     int temp = *a;     *a = *b;     *b = temp; }  // Function to sort an array of 0s, 1s and 2s void sort012(int arr[], int n) {     int lo = 0;     int hi = n - 1;     int mid = 0;      // Iterate till all the elements     // are sorted     while (mid <= hi) {         if (arr[mid] == 0)             swap(&arr[lo++], &arr[mid++]);         else if (arr[mid] == 1)             mid++;         else             swap(&arr[mid], &arr[hi--]);     } }  int main() {     int arr[] = { 0, 1, 2, 0, 1, 2 };     int n = sizeof(arr) / sizeof(arr[0]);      sort012(arr, n);      for (int i = 0; i < n; i++)         printf("%d ", arr[i]);      return 0; } 
Java
// Java program to sort an array of 0s, 1s and 2s  // using Dutch National Flag Algorithm  import java.util.ArrayList; import java.util.Arrays; class GfG {      // Function to sort an array of 0s, 1s and 2s     static void sort012(int[] arr) {         int n = arr.length;         int lo = 0;         int hi = n - 1;         int mid = 0, temp = 0;          // Iterate till all the elements are sorted         while (mid <= hi) {             if (arr[mid] == 0) {                 swap(arr, mid, lo);                 lo++;                 mid++;             }             else if (arr[mid] == 1) {                 mid++;             }             else {                 swap(arr, mid, hi);                 hi--;             }         }     } 	     static void swap(int[] arr, int i, int j) {         int temp = arr[i];         arr[i] = arr[j];         arr[j] = temp;     }      public static void main(String[] args) {         int[] arr = { 0, 1, 2, 0, 1, 2 };         sort012(arr);          for (int i = 0; i < arr.length; i++)             System.out.print(arr[i] + " ");     } } 
Python
# Python program to sort an array of 0s, 1s and 2s  # using Dutch National Flag Algorithm  # Function to sort an array of 0s, 1s and 2s def sort012(arr):     n = len(arr)     lo = 0     hi = n - 1     mid = 0      # Iterate till all the elements are sorted     while mid <= hi:       if arr[mid] == 0:         arr[lo], arr[mid] = arr[mid], arr[lo]         lo = lo + 1         mid = mid + 1                elif arr[mid] == 1:         mid = mid + 1                else:         arr[mid], arr[hi] = arr[hi], arr[mid]         hi = hi - 1              return arr  arr = [0, 1, 2, 0, 1, 2] arr = sort012(arr)  for x in arr:     print(x, end=" ") 
C#
// C# program to sort an array of 0s, 1s and 2s  // using Dutch National Flag Algorithm  using System;  class GfG {      // Function to sort an array of 0s, 1s and 2s     static void sort012(int[] arr) {         int n = arr.Length;         int lo = 0;         int hi = n - 1;         int mid = 0;          // Iterate till all the elements         // are sorted         while (mid <= hi) {             if (arr[mid] == 0) {                 swap(arr, lo, mid);                 lo++;                 mid++;             }             else if (arr[mid] == 1) {                 mid++;             }             else {                 swap(arr, mid, hi);                 hi--;             }         }     }      static void swap(int[] arr, int i, int j) {         int temp = arr[i];         arr[i] = arr[j];         arr[j] = temp;     }      static void Main() {         int[] arr = { 0, 1, 2, 0, 1, 2 };         sort012(arr);          foreach(int num in arr) Console.Write(num + " ");     } } 
JavaScript
// JavaScript program to sort an array of 0s, 1s and 2s  // using Dutch National Flag Algorithm  // Function to sort an array of 0s, 1s and 2s function sort012(arr) {     let lo = 0;     let hi = arr.length - 1;     let mid = 0;      // Iterate till all the elements are sorted     while (mid <= hi) {        	 if(arr[mid] === 0) {             [arr[lo], arr[mid]] = [arr[mid], arr[lo]];             lo++;             mid++;          }          else if(arr[mid] === 1) {          	mid++;          }          else {             [arr[mid], arr[hi]] = [arr[hi], arr[mid]];             hi--;          }     } }  let arr = [0, 1, 2, 0, 1, 2]; sort012(arr); console.log(arr.join(' ')); 

Output
0 0 1 1 2 2 



Next Article
Sort an array of 0s, 1s and 2s - Dutch National Flag Problem

K

kartik
Improve
Article Tags :
  • Sorting
  • DSA
  • Arrays
  • Microsoft
  • Amazon
  • Adobe
  • Morgan Stanley
  • Qualcomm
  • Walmart
  • Yatra.com
  • Snapdeal
  • Paytm
  • Hike
  • MAQ Software
  • SAP Labs
  • MakeMyTrip
  • Ola Cabs
Practice Tags :
  • Adobe
  • Amazon
  • Hike
  • MakeMyTrip
  • MAQ Software
  • Microsoft
  • Morgan Stanley
  • Ola Cabs
  • Paytm
  • Qualcomm
  • SAP Labs
  • Snapdeal
  • Walmart
  • Yatra.com
  • Arrays
  • Sorting

Similar Reads

    Sorting Algorithms
    A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
    3 min read
    Introduction to Sorting Techniques – Data Structure and Algorithm Tutorials
    Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
    3 min read

    Most Common Sorting Algorithms

    Selection Sort
    Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
    8 min read
    Bubble Sort Algorithm
    Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
    8 min read
    Insertion Sort Algorithm
    Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
    9 min read
    Merge Sort - Data Structure and Algorithms Tutorials
    Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
    14 min read
    Quick Sort
    QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
    12 min read
    Heap Sort - Data Structures and Algorithms Tutorials
    Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
    14 min read
    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
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