This was one of the interview questions that I was asked. The question is to sort an array which contains only binary numbers
Ex: int arr[] = {1,0,1,1,1,0,0,1,0,0,1,0};
Ex: int arr[] = {1,0,1,1,1,0,0,1,0,0,1,0};
Here is the program in java to do the same. One way is to start from both ends of the array and swap 1s from left to 0s in right until we reach the middle of the array.
public static void srtBnryAry(int[] toSort) {
int begin = 0;
int end = toSort.length - 1;
while (begin < end) {
// if you find zero at left, keep moving
if (0 == toSort[begin]) {
begin++
}
// if one occurs to the left then move from right until you find a zero
else if (1 == toSort[end]) {
end--;
}
// swap when you find a one at left and zero at right
else {
toSort[begin] = 0;
toSort[end] = 1;
}
}
}
------------------------------
public static void main(String[] args) {
int[] bin = new int[] {1,0,1,1,1,0,0,1,0,0,1,0};
srtBnryAry(bin);
System.out.println(Arrays.toString(bin));
}
No comments:
Post a Comment