Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given an array numbers, write a java function to move all 0's to the end of
- it while maintaining the relative order of the non-zero elements.
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
- Example:
- Input: {0,1,0,12,11}
- Output: {1,12,11,0,0}
- */
- public class AlogProblem {
- public static void moveZeros(int [] numbers) {
- final int value = 0;
- int arrLength = numbers.length;
- int i = arrLength - 1;
- int current ;
- int temp;
- while( 0 <= i) {
- if(numbers[i] == value) {
- temp = numbers[i];
- current = i;
- do {
- int index = current + 1;
- if(index == arrLength) break;
- if(numbers[index] != value) {
- numbers[current] = numbers[index];
- numbers[index] = temp;
- current++;
- } else {
- break;
- }
- } while(true);
- }
- i--;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement