Segregate 0’s and 1’s and 2’s in array in C++

Segregate 0’s, 1’s and 2’s in an array

On this page we will discuss the C program for segregate 0’s, 1’s and 2’s in an array in C++ . We are given an array  containing 0,1 and 2 and we have arrange them such that all the 0’s are placed before all the 1’s, and all the 1’s are placed before all the 2’s. We will discuss how to solve this problem using different methods along with algorithm and code in C++

Segregate 0’s and 1’s in an array

Segregate 0’s, 1's and 2’s in an array in C++

The task at hand is to sort an array of integers that exclusively consists of 0’s, 1’s, and 2’s, with the goal of segregating them in a specific order. The desired arrangement entails placing all the 0’s before the 1’s, and all the 1’s before the 2’s. This particular challenge is commonly known as the Dutch National Flag problem, drawing inspiration from the three bands of color in the Dutch flag. In this discourse, we will look  into two different approaches to tackle this problem.

  1. Brute Force Method
  2. Dutch National Flag Method
Segregate 0’s, 1's and 2’s in an array in C++-1

Brute force approach to segregate 0’s, 1’s, and 2’s in an array is to count the number of 0’s, 1’s, and 2’s in the array, and then overwrite the array with the correct number of each value

Algorithm for brute force

Here’s how the algorithm works:

  1. Initialize counters for 0’s, 1’s, and 2’s to 0.
  2. Loop through the array and count the occurrences of 0’s, 1’s, and 2’s.
  3. Store the counts in separate variables.
  4. Overwrite the array with the correct number of each value, starting with 0’s, then 1’s, then 2’s, using the stored counts.

Code for brute force method in C++

Run
#include <iostream>
using namespace std;

void segregate (int arr[], int n)
{
  int count_0 = 0, count_1 = 0, count_2 = 0;

  // Step 1: Count the number of 0's, 1's, and 2's
  for (int i = 0; i < n; i++)
    {
      if (arr[i] == 0)
	{
	  count_0++;
	}
      else if (arr[i] == 1)
	{
	  count_1++;
	}
      else if (arr[i] == 2)
	{
	  count_2++;
	}
    }

  // Step 2: Overwrite the array with the correct number of each value
  int i = 0;
  while (count_0 > 0)
    {
      arr[i] = 0;
      count_0--;
      i++;
    }
  while (count_1 > 0)
    {
      arr[i] = 1;
      count_1--;
      i++;
    }
  while (count_2 > 0)
    {
      arr[i] = 2;
      count_2--;
      i++;
    }
}

int main ()
{
  int arr[] = { 2, 0, 1, 2, 0, 1, 0, 2, 1 };
  int n = sizeof (arr) / sizeof (arr[0]);

  cout << "Array: ";
  for (int i = 0; i < n; i++)
    {
      cout << arr[i] << " ";
    }
  cout << endl;

  segregate (arr, n);

  cout << "Segregated array: ";
  for (int i = 0; i < n; i++)
    {
      cout << arr[i] << " ";
    }
  cout << endl;

  return 0;
}

Output

Array: 2 0 1 2 0 1 0 2 1 
Segregated array: 0 0 0 1 1 1 2 2 2 

One approach to segregate 0’s, 1’s, and 2’s in an array is to use the Dutch National Flag algorithm. The basic idea of this algorithm is to maintain three pointers to partition the array into three parts: the 0’s, the 1’s, and the 2’s.

Algorithm for dutch national flag algorithm

Here’s how the algorithm works:

  1. Initialize three pointers – low pointing to the beginning of the array, mid pointing to the current element being processed, and high pointing to the end of the array.
  2. While mid is less than or equal to high, repeat steps 3-7.
  3. Check if the value at arr[mid] is 0.
  4. If yes, swap the values at arr[mid] and arr[low], and increment both mid and low.
  5. If the value at arr[mid] is 1, move mid pointer to the next element.
  6. If the value at arr[mid] is 2, swap the values at arr[mid] and arr[high], and decrement high.
  7. Repeat steps 3-6 until mid becomes greater than high.
  8. The array is now segregated with 0’s on the left, 1’s in the middle, and 2’s on the right.

Code for dutch national flag method in C++

Run
#include <iostream>
using namespace std;

void dutchNationalFlag (int arr[], int n)
{
  int low = 0;			// pointer to the low end of the array
  int mid = 0;			// pointer to the current element being processed
  int high = n - 1;		// pointer to the high end of the array

  while (mid <= high)
    {
      if (arr[mid] == 0)
	{
	  // Swap arr[mid] and arr[low], increment both mid and low
	  swap (arr[mid], arr[low]);
	  mid++;
	  low++;
	}
      else if (arr[mid] == 1)
	{
	  // Move mid pointer to the next element
	  mid++;
	}
      else if (arr[mid] == 2)
	{
	  // Swap arr[mid] and arr[high], decrement high
	  swap (arr[mid], arr[high]);
	  high--;
	}
    }
}

int main ()
{
  int arr[] = { 2, 0, 1, 2, 0, 1, 0, 2, 1 };
  int n = sizeof (arr) / sizeof (arr[0]);

  cout << "Array: ";
  for (int i = 0; i < n; i++)
    {
      cout << arr[i] << " ";
    }
  cout << endl;

  dutchNationalFlag (arr, n);

  cout << "Segregated array: ";
  for (int i = 0; i < n; i++)
    {
      cout << arr[i] << " ";
    }
  cout << endl;

  return 0;
}

Output

Array: 2 0 1 2 0 1 0 2 1 
Segregated array: 0 0 0 1 1 1 2 2 2 

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

Introduction to Trees

Binary Trees

Binary Search Trees

Traversals

  • Traversal in Trees
  • Tree Traversals: Breadth-First Search (BFS) : C | C++ | Java
  • Tree Traversals: Depth First Search (DFS) : C | C++ | Java
  • Construct a Binary Tree from Postorder and Inorder

B – Trees

AVL Trees

  • AVL Trees
    • AVL Trees: Introduction
    • AVL Tree Insertion : C | C++ | Java
    • AVL Tree Deletion : C | C++ | Java
    • Insertion in a Binary Tree (Level Order) – C | C++ | Java
    • Searching in Binary Tree – C | C++ | Java
    • Searching in a Binary Search Tree – C | C++ | Java

Complete Programs for Trees

  • Depth First Traversals – C | C++ | Java
  • Level Order Traversal – C | C++Java
  • Construct Tree from given Inorder and Preorder traversals – C | C++Java
  • Construct Tree from given Postorder and Inorder traversals – C | C++Java
  • Construct Tree from given Postorder and Preorder traversal – C | C++Java
  • Find size of the Binary tree – C | C++Java
  • Find the height of binary tree – C | C++Java
  • Find maximum in binary tree – C | C++Java
  • Check whether two tree are identical- CC++Java
  • Spiral Order traversal of Tree- CC++Java
  • Level Order Traversal Line by Line – C | C++Java
  • Hand shaking lemma and some Impotant Tree Properties.
  • Check If binary tree if Foldable or not.- CC++Java
  • check whether tree is Symmetric – C| C++Java.
  • Check for Children-Sum in Binary Tree- C|C++Java
  • Sum of all nodes in Binary Tree- CC++ | Java
  • Lowest Common Ancestor in Binary Tree- CC++ | Java

Introduction to Trees

Binary Trees

Binary Search Trees

Traversals

  • Traversal in Trees
  • Tree Traversals: Breadth-First Search (BFS) : C | C++ | Java
  • Tree Traversals: Depth First Search (DFS) : C | C++ | Java
  • Construct a Binary Tree from Postorder and Inorder

B – Trees

AVL Trees

  • AVL Trees
    • AVL Trees: Introduction
    • AVL Tree Insertion :  C | C++ | Java
    • AVL Tree Deletion : C | C++ | Java
    • Insertion in a Binary Tree (Level Order) – C | C++ | Java
    • Searching in Binary Tree – C | C++ | Java
    • Searching in a Binary Search Tree – C | C++ | Java

Complete Programs for Trees

  • Depth First Traversals – C | C++ | Java
  • Level Order Traversal – C | C++Java
  • Construct Tree from given Inorder and Preorder traversals – C | C++Java
  • Construct Tree from given Postorder and Inorder traversals – C | C++Java
  • Construct Tree from given Postorder and Preorder traversal – C | C++Java
  • Find size of the Binary tree – C | C++Java
  • Find the height of binary tree – C | C++Java
  • Find maximum in binary tree – C | C++Java
  • Check whether two tree are identical- CC++Java
  • Spiral Order traversal of Tree- CC++Java
  • Level Order Traversal LIne by Line – C | C++Java
  • Hand shaking lemma and some Impotant Tree Properties.
  • Check If binary tree if Foldable or not.- CC++Java
  • check whether tree is Symmetric  C| C++Java.
  • Check for Children-Sum in Binary Tree- C|C++Java
  • Sum of all nodes in Binary Tree- CC++ | Java
  • Lowest Common Ancestor in Binary Tree. CC++ | Java