You are given a number (either 32 or 64 bit)containing some bit pattern (or numeric value). You have to place all the 0s in even position and 1s in odd position and if suppose number of 0s exceed the number of 1s or vice versa then keep them untouched. Generalize your solution for an N bit number.
It has to be done in O(n) time, without several single loops (only one pass) and O(1)space.
For e.g.
Input Number: 0 1 1 0 1 0 1 0 1 1 1 0 0 1 0 1 1
output number: 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1
Logic : We need to maintain two pointers – oddPtr which moves along the odd positions in the array and evenPtr which moves along the even positions. When we find an incorrect position, we swap this pointers and move along.
One interesting case is when one of the pointer moves past the last element, in that case, we have no way to compare the other pointer with. In this case, we simply swap one pointer with the other position.
public class ZeroOneArray {
public static void main(String args[]){
int[] a = {0 ,1 ,1 ,0 ,1 ,0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1};
int oddPtr = 1;
int evenPtr= 0;
while(true){
if((oddPtr > 0 && oddPtr < a.length-1)
&& (evenPtr>=0 && evenPtr<a.length-1)){
//Incorrect position found for both odd and even pointers
if(a[oddPtr]!=1 && a[evenPtr] !=0)
{
//Swap the incorrect positions
swap(a, evenPtr, oddPtr);
//Move both the pointers to two places.
oddPtr+=2; evenPtr+=2;
}
else
{
//Correct values at correct positions
//Just increment pointers
if(a[oddPtr] ==1)
oddPtr+=2;
if(a[evenPtr] ==0)
evenPtr+=2;
}
}
//This is the case where one of the pointers has reached the end
//so there is no way to find a mismatch pointer
//In that case, we simply swap odd with even and vice versa
else if ((evenPtr>a.length-1) && (oddPtr+2 < a.length-1)) {swap(a, oddPtr, oddPtr+2); oddPtr+=2;}
else if ((oddPtr>a.length-1) && (evenPtr+2 < a.length-1)) {swap(a, evenPtr, evenPtr+2); evenPtr+=2;}
else{break;}
}
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