You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You are given an integer array/list(ARR) of size N.
4
+
It contains only 0s, 1s and 2s.
5
+
Write a solution to sort this array/list in a 'single scan'.
6
+
'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.
7
+
Note: You need to change in the given array/list itself.
8
+
Hence, no need to return or print anything.
9
+
10
+
Input format : The first line contains an Integer 't' which denotes the number of test cases or queries to be run.
11
+
Then the test cases follow.
12
+
13
+
First line of each test case or query contains an integer 'N' representing the size of the array/list.
14
+
15
+
Second line contains 'N' single space separated integers(all 0s, 1s and 2s) representing the elements in the array/list. Output Format : For each test case, print the sorted array/list elements in a row separated by a single space.
16
+
17
+
Output for every test case will be printed in a separate line.
18
+
Constraints :
19
+
1 <= t <= 10^2 0 <= N <= 10^5
20
+
Time Limit: 1 sec
21
+
22
+
Sample Input 1: 1 7 0 1 2 0 2 0 1
23
+
Sample Output 1: 0 0 0 1 1 2 2
24
+
25
+
Sample Input 2: 2 5 2 2 0 1 1 7 0 1 2 0 1 2 0
26
+
Sample Output 2: 0 1 1 2 2 0 0 0 1 1 2 2
27
+
28
+
*/
29
+
#include<iostream>
30
+
usingnamespacestd;
31
+
32
+
voidsimplifiedsort012(int *arr, int n){
33
+
34
+
int i=0,nz=0,nt=n-1;
35
+
while(i<n &&i<=nt){
36
+
if(arr[i]==0){
37
+
int temp=arr[i];
38
+
arr[i]=arr[nz];
39
+
arr[nz]=temp;
40
+
nz++;
41
+
}
42
+
elseif(arr[i]==2){
43
+
int temp=arr[i];
44
+
arr[i]=arr[nt];
45
+
arr[nt]=temp;
46
+
nt--;
47
+
continue;
48
+
49
+
}
50
+
51
+
i++;
52
+
}
53
+
}
54
+
55
+
intmain(){
56
+
57
+
int n;
58
+
cout<<"Enter the size of the Array "<<endl;
59
+
cin>>n;
60
+
int *arr=newint[n];
61
+
cout<<"Enter Elements in the Array "<<endl;
62
+
for(int i=0;i<n;i++){
63
+
cin>>arr[i];
64
+
}
65
+
simplifiedsort012(arr,n);
66
+
return0;
67
+
}
68
+
69
+
/*
70
+
Explanation
71
+
👉🏼Take two variables as starting(nz) and ending(nt) depicting position of 0's and 2's to be swapped respectively
72
+
73
+
👉🏼Initialize nz as Starting Index i.e 0 and increment it after every swap
74
+
75
+
👉🏼Initialize nt as Ending Index i.e Size-1 and decrement it after every swap
76
+
77
+
Special Attention should be given to the following points :)
78
+
✨Swap 0's and increment nz & i
79
+
80
+
✨Swap 2's and increment nt but not i (ignore the updation of expression)
0 commit comments