Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

Β 

History

History
History
72 lines (60 loc) Β· 1.55 KB

File metadata and controls

72 lines (60 loc) Β· 1.55 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
67
68
69
70
71
72
import java.util.Arrays;
public class SortBinaryArray {
// O(N) Time | O(1) Space
public static void sortBinaryArr(int[] arr) {
int zeroid = 0, nonzero = 0;
while (zeroid < arr.length && nonzero < arr.length) {
if (arr[zeroid] != 0) {
zeroid++;
}
if (arr[nonzero] != 1) {
nonzero++;
}
if (zeroid < arr.length && nonzero < arr.length) {
if (arr[zeroid] == 0 && arr[nonzero] == 1) {
swap(arr, zeroid, nonzero);
}
}
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// approach 2- O(N) Time | O(1) Space
public static void sortBinaryArr2(int[] arr) {
int zeroth = 0;
// replacing all initial items with zero with total zeros available
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
arr[zeroth] = 0;
zeroth++;
}
}
// making all 1's after all zeros
for (int i = zeroth; i < arr.length; i++) {
arr[i] = 1;
}
}
// using partitioning logic of quick sort
// O(N) time | O(1) Space
public static void sortBinaryArr3(int[] arr) {
int pivotElement = 1;
int pivotIndex = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < pivotElement) {
swap(arr, i, pivotIndex);
pivotIndex++;
}
}
}
public static void main(String[] args) {
// int[] arr = { 1, 0, 0, 1, 0, 1, 0, 1, 1, 1 };
// int[] arr = { 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0 };
// int[] arr = { 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0 };
int[] arr = { 1, 1, 0, 1, 0, 0 };
sortBinaryArr3(arr);
System.out.println(Arrays.toString(arr));
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.