-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSegregate0sand1s.js
50 lines (40 loc) · 1.04 KB
/
Segregate0sand1s.js
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
// You are given an array of 0s and 1s in random order.
// Segregate 0s on left side and 1s on right side of the array
// [Basically you have to sort the array]. Traverse array only once.
// Approach 1 (The array is traversed multiple times)-->Not Efficient
function Segregate0sand1s(arr) {
let length = arr.length;
let count0 = 0;
for (let i = 0; i < length; i++) {
if (arr[i] === 0) {
count0++;
}
}
for (let i = 0; i < count0; i++) {
arr[i] = 0;
}
for (let i = count0; i < length; i++) {
arr[i] = 1;
}
console.log(arr);
}
const arr = [0, 1, 0, 1, 0, 1, 0, 0, 0, 1];
Segregate0sand1s(arr);
// Approach 2()-->Efficient
function Segregate0sand1s(arr) {
let low = 0;
let high = arr.length - 1;
while (low < high) {
while (arr[low] == 0 && low < high) low++;
while (arr[high] == 1 && low < high) high--;
if (low < high) {
arr[low] = 0;
arr[high] = 1;
low++;
high--;
}
}
return arr;
}
const arr = [0, 1, 0, 1, 0, 1, 0, 0, 0, 1];
console.log(Segregate0sand1s(arr));