Skip to content

Commit

Permalink
Create Sort 0s, 1s and 2s
Browse files Browse the repository at this point in the history
  • Loading branch information
dishathakurata authored Dec 5, 2024
1 parent 198c54b commit 6578005
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions Sort 0s, 1s and 2s
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
//Sort 0s, 1s and 2s

import java.io.*;
import java.util.*;

class GFG {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());

while(t-- > 0) {
String input = br.readLine();
String[] inputArray = input.split("\\s+");
int a[] = new int[inputArray.length];

for(int i = 0; i < a.length; i++) {
a[i] = Integer.parseInt(inputArray[i]);
}

Solution ob = new Solution();
ob.sort012(a);

for(int num : a) {
System.out.print(num + " ");
}
System.out.println();
System.out.println("~");
}
}
}

class Solution {
public void sort012(int[] arr) {
int countZero = 0, countOne = 0, countTwo = 0, n = arr.length;

for(int i = 0; i < n; i++) {
if(arr[i] == 0) {
countZero++;
}
else if(arr[i] == 1) {
countOne++;
}
else {
countTwo++;
}
}

int j = 0;

while(countZero > 0) {
arr[j] = 0;
countZero--;
j++;
}

while(countOne > 0) {
arr[j] = 1;
countOne--;
j++;
}

while(countTwo > 0) {
arr[j] = 2;
countTwo--;
j++;
}
}
}

0 comments on commit 6578005

Please sign in to comment.