function sort012(arr, N) { let one= 0 ; let zero= 0 ; let two = 0 ; for ( let i= 0 ; i<N; i++){ if (arr[i]== 0 ){ zero++; } else if (arr[i]== 1 ){ one++; } else { two++; } } for ( let k= 0 ; k<N; k++){ if (zero != 0 ){ arr[k]= 0 ; zero-- } else if (one != 0 ){ arr[k]= 1 ; one-- } else if (two != 0 ){ arr[k]= 2 ; two-- } } console.log(arr) } sort012([ 0 , 2 , 1 , 2 , 0 ], 5 ); Result: (5) [0, 0, 1, 2, 2] We will count total 1s , 0s and 2s and then in second iteration we will replace the array with count values by using another look