-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsort012.java
66 lines (56 loc) · 1.07 KB
/
sort012.java
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
// Java implementation of the approach
import java.io.*;
class sort012 {
// Utility function to print the contents of an array
static void printArr(int arr[], int n)
{
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
// Function to sort the array of 0s, 1s and 2s
static void sortArr(int arr[], int n)
{
int i, cnt0 = 0, cnt1 = 0, cnt2 = 0;
// Count the number of 0s, 1s and 2s in the array
for (i = 0; i < n; i++) {
switch (arr[i]) {
case 0:
cnt0++;
break;
case 1:
cnt1++;
break;
case 2:
cnt2++;
break;
}
}
// Update the array
i = 0;
// Store all the 0s in the beginning
while (cnt0 > 0) {
arr[i++] = 0;
cnt0--;
}
// Then all the 1s
while (cnt1 > 0) {
arr[i++] = 1;
cnt1--;
}
// Finally all the 2s
while (cnt2 > 0) {
arr[i++] = 2;
cnt2--;
}
// Print the sorted array
printArr(arr, n);
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 2,2,2,2,0,0,1,0};
int n = arr.length;
sortArr(arr, n);
}
}
// This code is contributed by shubhamsingh10