Skip to content

Commit f32b671

Browse files
committed
Sort array of 0,1 and 2s
1 parent f523138 commit f32b671

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

SortArrayOf0s1sand2s.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Given an array arr[] consisting 0s, 1s and 2s.
2+
// The task is to write a function that sorts the given array.
3+
// The functions should put all 0s first, then all 1s and all 2s in last.
4+
5+
// Approach 1()-->less Efficient
6+
function sortArrayOf0s1sand2s(arr) {
7+
count0 = 0;
8+
count1 = 0;
9+
count2 = 0;
10+
11+
for (let i = 0; i < arr.length; i++) {
12+
if (arr[i] === 0) {
13+
count0++;
14+
} else if (arr[i] === 1) {
15+
count1++;
16+
} else {
17+
count2++;
18+
}
19+
}
20+
21+
let i = 0;
22+
23+
while (count0 > 0) {
24+
arr[i++] = 0;
25+
count0--;
26+
}
27+
28+
while (count1 > 0) {
29+
arr[i++] = 1;
30+
count1--;
31+
}
32+
33+
while (count2 > 0) {
34+
arr[i++] = 2;
35+
count2--;
36+
}
37+
return arr;
38+
}
39+
40+
const arr = [2, 1, 0, 0, 1, 2, 0, 2, 1, 0];
41+
console.log(sortArrayOf0s1sand2s(arr));
42+
43+
// Approach 2()-->More efficient
44+
function sortArrayOf0s1sand2s(arr) {
45+
let left = 0;
46+
let mid = 0;
47+
let right = arr.length - 1;
48+
while (mid <= right) {
49+
if (arr[mid] === 0) {
50+
[arr[mid], arr[left]] = [arr[left], arr[mid]];
51+
left++;
52+
mid++;
53+
} else if (arr[mid] === 1) {
54+
mid++;
55+
} else {
56+
[arr[mid], arr[right]] = [arr[right], arr[mid]];
57+
right--;
58+
}
59+
}
60+
return arr;
61+
}
62+
63+
const arr = [2, 1, 0, 0, 1, 2, 0, 2, 1, 0];
64+
console.log(sortArrayOf0s1sand2s(arr));

0 commit comments

Comments
 (0)