Return an array that contains the exact same numbers as the given array, but rearranged so that all the zeros are grouped at the start of the array. The order of the non-zero numbers does not matter. So {1, 0, 0, 1} becomes {0 ,0, 1, 1}. You may modify and return the given array or make a new array.
Asked
Active
Viewed 50 times
-3
-
1Voting to close this question, because it is currently unclear what your exact problem with this assignment is. – Tom May 17 '15 at 10:59
3 Answers
1
Keep 2 pointers, one at the start and the other which searches for 0s. If a zero is found, swap them, and move the pointers forward.

shruti1810
- 3,920
- 2
- 16
- 28
0
This probably isn't the fastest code, but for smaller arrays but I'd do something like this:
for(int index = 0; index<array.length; index++ ){
for(int search = index+1; search<array.length; search++){
if(array[search]==0){
int tempStorage = array[index];
array[index]= array[search];
array[search]= tempStorage;
}
}
}

themiDdlest
- 96
- 1
- 13
0
Sort your array with a custom comparator (See https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort(T[],%20java.util].Comparator).
In your comparator if it's not 0 then use the default int compare (See https://stackoverflow.com/a/9150459/241294).
Something like:
int compare(int a, int b)
{
if (a == 0 && b == 0)
return 0;
if (a == 0)
return -1;
if (b == 0)
return 1;
else
return Integer.compareTo(a, b);
}