Created
December 19, 2016 01:51
-
-
Save kvreem/ec9d4fb29864bfefdcd1f6058cce260b to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Created by Kareem on 12/18/16. | |
*/ | |
public class swap1 { | |
public static void main (String[] args) { | |
int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}; | |
swapZeros(arr); | |
for(int i = 0; i < arr.length; i++){ | |
System.out.print(arr[i]); | |
} | |
} | |
public static void swapZeros(int[] nums){ | |
int count = 0; // Count of non-zero elements | |
// Traverse the array. If element encountered is | |
// non-zero, then replace the element at index 'count' | |
// with this element | |
for (int i = 0; i < nums.length; i++) | |
if (nums[i] != 0) | |
nums[count++] = nums[i]; // here count is incremented | |
// Now all non-zero elements have been shifted to | |
// front and 'count' is set as index of first 0. | |
// Make all elements 0 from count to end. | |
while (count < nums.length) | |
nums[count++] = 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment