Skip to content

Instantly share code, notes, and snippets.

@SIRHAMY
Created January 8, 2016 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SIRHAMY/9bbb9218ad360c40ea04 to your computer and use it in GitHub Desktop.
Save SIRHAMY/9bbb9218ad360c40ea04 to your computer and use it in GitHub Desktop.
Short method that takes in an integer array and moves all the zeroes to the right-most indices.
public static void zeroRightShift(int[] A) {
if(A == null) return;
int zeroPtr = A.length - 1;
while(zeroPtr >= 0) {
if(A[zeroPtr] != 0) break;
zeroPtr--;
}
int findPtr = zeroPtr - 1;
while(findPtr >= 0) {
if(A[findPtr] == 0) {
A[findPtr] = A[zeroPtr]; //Put nonzero value at index we found zero in
A[zeroPtr] = 0;
zeroPtr--;
}
findPtr--;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment