Run
import java.util.*;
public
class Main {
public
static void arrange012(int[] arr) { // we arrange 0 1 2 iteratively
int i = 0, j = 0, k = arr.length - 1;
// 0 to j-1 ==> All Zeroes
while (i <= k) {
if (arr[i] == 0) {
swap(arr, i, j);
i++;
j++;
} else if (arr[i] == 1) {
i++;
} else {
swap(arr, i, k);
k--;
}
}
}
// used for swapping ith and jth elements of array
public
static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// main function
public
static void main(String[] args) throws Exception {
Scanner scn = new Scanner(System.in);
int n = 4;
int[] arr = new int[]{ 1,0,0,1};
arrange012(arr);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
public static void main(String[] args) {
int[] a={1,0,2,1,1,0,2,1,0};
int b0=0,b1=0,b2=0;
for(int i=0;i<a.length;i++){
if(a[i]==0) b0++;
else if(a[i]==1) b1++;
else{
b2++;
}
}
for(int i=0;i<b0;i++){
System.out.print("0"+" ");
}
for(int i=0;i<b1;i++){
System.out.print("1"+" ");
}
for(int i=0;i<b2;i++){
System.out.print("2"+" ");
}
}
Kindly join our Discord channel if you have any technical query.
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner scn=new Scanner(System.in);
int n=scn.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=scn.nextInt();
}
int i=0,j=0,k=arr.length-1;
while(j<=k){
if(arr[j]==0){
swap(arr,i,j);
i++;
j++;
}
else if(arr[j]==2){
swap(arr,j,k);
k–;
}
else{
j++;
}
}
for(int val:arr){
System.out.print(val+" ");
}
}
public static void swap(int[] arr,int i,int j){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}