- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort an arrays of 0’s, 1’s and 2’s using C++
Given an array of 0, 1, and 2, sort the elements in an order such that all the zeros come first before 1 and all the 2’s in the end. We have to sort all the elements of the array in-place.
We can solve this problem using DNF (Dutch National Flag) Sorting Algorithm. For example,
Input-1 −
arr[ ]= {2,0,0,1,2,1 }
Output −
0 0 1 1 2 2
Explanation − Sorting the given array of elements containing 0,1 and 2 using DNF Sorting Algorithm, it will print the output as {0,0,1,1,2,2}.
Input-2 −
arr[ ]= {0,1,1,2,1,1,0}
Output −
0 0 1 1 1 1 2
Explanation − Sorting the given array of elements containing 0,1 and 2 using the DNF Sorting Algorithm, it will print the output as {0,0,1,1,1,1,2}.
Approach to solve this Problem
In the given array of 0, 1 and 2, we can use the DNF sorting algorithm.
DNF Sorting Algorithm − The algorithm requires 3 pointers to iterate throughout the array by swapping the necessary elements.
Create a low pointer at the beginning of the array and high pointer pointing at the end of the array.
Find the Midpoint of the array and create a mid pointer as well that iterates from the beginning of the array till the end.
If the mid-pointer of the array is ‘0’, then swap the element pointing at low. Increment the low pointer and mid pointer.
If the mid-pointer of the array is ‘2’, then swap it with the element pointing at the high. Increment the mid pointer and decrement the high pointer.
If the mid-pointer of the array is ‘1’, then increase the mid pointer.
Example
#include<iostream> using namespace std; void dnfsort(int a[], int n){ int low= 0; int high= n-1; int mid=0; while(mid<=high){ if(a[mid]==0){ swap(a[mid],a[low]); mid++; low++; } if(a[mid]==1){ mid++; } if(a[mid]==2){ swap(a[mid],a[high]); high--; } } } int main(){ int a[]= {1,0,0,2,1,1,0,0,1}; int n= sizeof(a)/sizeof(int); dnfsort(a,n); for(int i=0;i<n;i++){ cout<<a[i]<<" "; } return 0; }
Output
Running the above code will generate the output as,
0 0 0 0 1 1 1 1 2