Problem : Given an array of 0’s and 1’s. Arrange the array such that
all 0’s are placed in the front and 1’s are placed in the back. Do this in o(n)
Algorithm : Just check where the correct position of the 0 and 1 should be using two pointers. leftPtr runs from 0 to n and rightPtr runs backward from n to 0. When there is a inconsistency of 0 and 1 placement, we swap them.
public class ZeroOneArrayArrange {
public static void main(String[] args) {
int[] a = {1,1,0,0,1,1,0,0,0,0,1};
int leftPtr=0;
int rightPtr = a.length-1;
for(;leftPtr<rightPtr;){
if(a[leftPtr] == 0)
leftPtr++;
if(a[rightPtr]==1)
rightPtr--;
if(a[leftPtr]==1 && a[rightPtr]==0 && leftPtr<rightPtr) {
swap(a,leftPtr,rightPtr);
}
for(int i=0;i<=a.length-1;i++){
System.out.print(","+a[i]);
}
}
private static void swap(int[] a, int even, int odd){
int tmp = a[even];
a[even] = a[odd];
a[odd] = tmp;
}
}
0 comments:
Post a Comment