Sort an array of 0 s , 1 s , 2 s and 3 s | 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
function sortArray ( arr , N ) { var i = 0 , j = N - 1 , mid = 0 ; while ( mid <= j ) { if ( arr [ mid ] == 0 ) { var temp = arr [ i ] ; arr [ i ] = arr [ mid ] ; arr [ mid ] = temp ; i ++ ; mid ++ ; } else if ( arr [ mid ] == 3 ) { var temp = arr [ mid ] ; arr [ mid ] = arr [ j ] ; arr [ j ] = temp ; j -- ; } else if ( arr [ mid ] == 1 arr [ mid ] == 2 ) { mid ++ ; } } while ( i <= j ) { if ( arr [ i ] == 2 ) { var temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; j -- ; } else { i ++ ; } } for ( i = 0 ; i < N ; i ++ ) { document . write ( arr [ i ] + " " ) ; } } var arr = [ 3 , 2 , 1 , 0 , 2 , 3 , 1 , 0 ] ; var N = arr . length ; sortArray ( arr , N ) ;