Skip to content

Instantly share code, notes, and snippets.

@mukhtiarahmed
Last active September 27, 2019 09:44
Show Gist options
  • Save mukhtiarahmed/b2e02fb71c567369b38bc96275a8ae38 to your computer and use it in GitHub Desktop.
Save mukhtiarahmed/b2e02fb71c567369b38bc96275a8ae38 to your computer and use it in GitHub Desktop.
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}
/*
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--;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment