Skip to content

Commit 641f71e

Browse files
Sorting Binary Array using couting sort
1 parent 00d5de1 commit 641f71e

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.java4u.ds.arrays.TechDelight;
2+
3+
public class SortBinaryArray {
4+
5+
public static void sortBinaryArray(int[] arr, int n) {
6+
int zerosCount = 0;
7+
for (int a : arr) {
8+
if (a == 0) {
9+
zerosCount++;
10+
}
11+
}
12+
int k = 0;
13+
while (zerosCount-- != 0) {
14+
arr[k++] = 0;
15+
}
16+
while (k < n) {
17+
arr[k++] = 1;
18+
}
19+
}
20+
21+
private static void print(int arr[]) {
22+
for (int a : arr) {
23+
System.out.print(a + " ");
24+
}
25+
System.out.println();
26+
}
27+
28+
public static void main(String[] args) {
29+
int[] arr = { 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1 };
30+
print(arr);
31+
sortBinaryArray(arr, arr.length - 1);
32+
print(arr);
33+
}
34+
35+
}

0 commit comments

Comments
 (0)