-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0_1_Sort.txt
86 lines (69 loc) · 2.29 KB
/
0_1_Sort.txt
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
Sort 0 1
Send Feedback
You have been given an integer array/list(ARR) of size N that contains only integers, 0 and 1. Write a function to sort this array/list. Think of a solution which scans the array/list only once and don't require use of an extra array/list.
Note:
You need to change in the given array/list itself. Hence, no need to return or print anything.
Input format :
The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.
First line of each test case or query contains an integer 'N' representing the size of the array/list.
Second line contains 'N' single space separated integers(all 0s and 1s) 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.
Output for every test case will be printed in a separate line.
Constraints :
1 <= t <= 10^2
0 <= N <= 10^5
Time Limit: 1 sec
Sample Input 1:
1
7
0 1 1 0 1 0 1
Sample Output 1:
0 0 0 1 1 1 1
Sample Input 2:
2
8
1 0 1 1 0 1 0 1
5
0 1 0 1 0
Sample Output 2:
0 0 0 1 1 1 1 1
0 0 0 1 1 Method 1:
public class Solution {
public static void sortZeroesAndOne(int[] arr) {
//Your code goes here
int n = arr.length;
int count = 0; // counts the no of zeros in arr
for (int i = 0; i < n; i++) {
if (arr[i] == 0)
count++;
}
// loop fills the arr with 0 until count
for (int i = 0; i < count; i++)
arr[i] = 0;
// loop fills remaining arr space with 1
for (int i = count; i < n; i++)
arr[i] = 1;
}
}
Method 2:
public class Solution {
public static void sortZeroesAndOne(int[] arr) {
//Your code goes here
int n = arr.length;
int[] a = new int[n];
int start = 0;
int end = n-1;
for(int i=0; i<n; i++){
if(arr[i]==0){
a[start]=0;
start++;
}else if(arr[i]==1){
a[end]=1;
end--;
}
}
for(int i=0;i<n;i++){
arr[i]=a[i];
}
}