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