-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSort 0 1 2.java
More file actions
64 lines (41 loc) · 1.23 KB
/
Copy pathSort 0 1 2.java
File metadata and controls
64 lines (41 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
class Ideone{
//https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s/0/?ref=self
public static Scanner scn = new Scanner(System.in);
public static void main (String[] args) throws java.lang.Exception{
int T = scn.nextInt();
while(T-- > 0){
int N = scn.nextInt();
//int[] arr = new int[N];
ArrayList<Integer> list = new ArrayList<>();
for(int i = 0; i < N; i++)
list.add(scn.nextInt());
int zeroEndIdx = -1;
int ones = 0;
for(int i = 0; i < N; i++){
int num = list.get(i);
if(num == 0){
//increase end index of zero
zeroEndIdx++;
//swap current zero with updated index
Collections.swap(list, i, zeroEndIdx);
int swapped = list.get(i);
//if swapped element is one, place it in right place
if(swapped == 1)
Collections.swap(list, i, zeroEndIdx + ones);
}else if(num == 1){
ones++;
Collections.swap(list, i, zeroEndIdx + ones);
} else {
//when num is 2 do nothing
}
}
for(int item : list)
System.out.print(item + " ");
System.out.println();
}
}
}