Created
April 13, 2014 06:09
-
-
Save gabhi/10571278 to your computer and use it in GitHub Desktop.
Move all zeroes to end of array
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
// Function which pushes all zeros to end of an array. | |
void pushZerosToEnd(int arr[], int n) | |
{ | |
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 < n; i++) | |
if (arr[i] != 0) | |
arr[count++] = arr[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 < n) | |
arr[count++] = 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment