Thursday, 19 August 2021

Sort 0s, 1s, 2s

 package demoTest;


public class Array1 {

public static void main(String[] args) {

// TODO Auto-generated method stub

int arr[] = new int[] {1, 0, 2, 2, 0, 1, 2, 0, 0, 2, 1, 0, 2, 0, 1, 0, 0, 2, 0, 1};

 

int n = arr.length;

 

//output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]

int count0 = 0;

int count1 =0;

int count2 =0;

for(int i =0; i<n; i++) {

if(arr[i]== 0) {

count0 ++;

}

else if(arr[i]== 1) {

count1 ++;

}

}

int l1 = count0+ count1;

count2 = n - ( count0 + count1);

for(int i = 0; i< count0; i++) {

arr[i]=0;

}

for(int i = count0; i< l1; i++) {

arr[i]=1;

}

for(int i = l1; i< n; i++) {

arr[i]=2;

}

for(int i = 0; i< n; i++) {

System.out.print(arr[i] + " ");

}

}

}
























     


No comments:

Post a Comment