Maintaining count : O(n) two traversals
Single scan : O(n)
public static void main(String[] args) {
int a[]={0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1};
int i=0,j=a.length-1;
while(i<j){
while(a[i]==0 && i<j)
i++;
while(a[j]==1 && i<j)
j--;
if(i<j){
a[i]=0;
a[j]=1;
i++;
j--;
}
}
for(int b : a)
System.out.print(b);
}
}
Single scan : O(n)
public static void main(String[] args) {
int a[]={0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1};
int i=0,j=a.length-1;
while(i<j){
while(a[i]==0 && i<j)
i++;
while(a[j]==1 && i<j)
j--;
if(i<j){
a[i]=0;
a[j]=1;
i++;
j--;
}
}
for(int b : a)
System.out.print(b);
}
}
Can use QuickSort partitioning algorithm also for doing the same !!!
No comments:
Post a Comment