-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
30 lines (25 loc) · 796 Bytes
/
Copy pathsolution.java
File metadata and controls
30 lines (25 loc) · 796 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
class Solution {
void segregate0and1(int[] arr) {
int left = 0;
int right = arr.length - 1;
// Continue until both pointers cross each other
while (left < right) {
// Move left pointer forward if element is 0
while (left < right && arr[left] == 0) {
left++;
}
// Move right pointer backward if element is 1
while (left < right && arr[right] == 1) {
right--;
}
// Swap misplaced values
if (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
}
}