-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortBinary.java
More file actions
41 lines (33 loc) · 807 Bytes
/
Copy pathSortBinary.java
File metadata and controls
41 lines (33 loc) · 807 Bytes
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
//sort binary(only 0 and 1) array in linear time:
import java.util.Arrays;
class SortBinary
{
// Function to sort a binary array in linear time
public static void sort(int[] A)
{
// count number of 0's
int zeros = 0;
for (int value: A)
{
if (value == 0) {
zeros++;
}
}
// put 0's at the beginning
int k = 0;
while (zeros-- != 0) {
A[k++] = 0;
}
// fill all remaining elements by 1
while (k < A.length) {
A[k++] = 1;
}
}
public static void main (String[] args)
{
int[] A = { 0,1,1,0,1,0,0};
sort(A);
// print the rearranged array
System.out.println(Arrays.toString(A));
}
}