Skip to content

Commit a151ddf

Browse files
authored
Create 10 : Sort 0 1 2
1 parent 029d013 commit a151ddf

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Arrays - 2/10 : Sort 0 1 2

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
"Sort 0 1 2"
3+
You are given an integer array/list(ARR) of size N. It contains only 0s, 1s and 2s. Write a solution to sort this array/list in a 'single scan'.
4+
'Single Scan' refers to iterating over the array/list just once or to put it in other words, you will be visiting each element in the array/list just once.
5+
Note:
6+
You need to change in the given array/list itself. Hence, no need to return or print anything.
7+
Input format :
8+
The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.
9+
10+
First line of each test case or query contains an integer 'N' representing the size of the array/list.
11+
12+
Second line contains 'N' single space separated integers(all 0s, 1s and 2s) representing the elements in the array/list.
13+
Output Format :
14+
For each test case, print the sorted array/list elements in a row separated by a single space.
15+
16+
Output for every test case will be printed in a separate line.
17+
Constraints :
18+
1 <= t <= 10^2
19+
0 <= N <= 10^5
20+
Time Limit: 1 sec
21+
Sample Input 1:
22+
1
23+
7
24+
0 1 2 0 2 0 1
25+
Sample Output 1:
26+
0 0 0 1 1 2 2
27+
Sample Input 2:
28+
2
29+
5
30+
2 2 0 1 1
31+
7
32+
0 1 2 0 1 2 0
33+
Sample Output 2:
34+
0 1 1 2 2
35+
0 0 0 1 1 2 2
36+
*/
37+
38+
public class Solution {
39+
40+
public static void sort012(int[] arr){
41+
int nZ=0,nT=arr.length-1;
42+
int tempforTwo=0;
43+
int tempforZero=0;
44+
int i=0;
45+
while(i<=nT){
46+
if(arr[i]==0){
47+
tempforZero=arr[nZ];
48+
arr[nZ]=arr[i];
49+
arr[i]=tempforZero;
50+
i++;
51+
nZ++;
52+
}
53+
else if(arr[i]==2){
54+
tempforTwo=arr[nT];
55+
arr[nT]=arr[i];
56+
arr[i]=tempforTwo;
57+
nT--;
58+
}
59+
else
60+
i++;
61+
}
62+
}
63+
64+
}

0 commit comments

Comments
 (0)