-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort0sAnd1s.java
More file actions
40 lines (37 loc) · 847 Bytes
/
Copy pathsort0sAnd1s.java
File metadata and controls
40 lines (37 loc) · 847 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
//Question: sort the array in ascending order where the elements only contains 0s and 1s.
package arrays;
public class sort0sAnd1s {
public static void main(String[] args) {
int [] arr={1, 1, 0, 1, 1, 0, 0, 1, 0, 0};
// Method 1:
// int noOfZeros=0;
// for (int i=0; i<arr.length; i++){
// if(arr[i]==0) noOfZeros++;
// }
// for(int i=0; i<noOfZeros; i++){
// arr[i]=0;
// }
// for(int i=noOfZeros; i<arr.length; i++){
// arr[i]=1;
// }
// for(int ele : arr){
// System.out.print(ele+" ");
// }
// METHOD 2:
int n=arr.length;
int i=0, j=n-1;
while(i<j){
if(arr[i]==0) i++;
else if(arr[j]==1) j--;
else if(arr[i]==1 && arr[j]==0){
arr[i]=0;
arr[j]=1;
i++;
j--;
}
}
for(int ele : arr){
System.out.print(ele+" ");
}
}
}