Created
January 8, 2016 05:40
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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