We have been given an array, which contains random numbers, including zero. We have to move all zeros at the end of the array.
Key Point: Move element when scan, put zeros after dest pointer.
http://www.geeksforgeeks.org/move-zeroes-end-array/
The algorithm is simple, we take two indices , one to loop through the entire array, and another to keep track of the non-zero elements. Once we loop through all the elements, we can fill the remaining spaces with zeros.
Key Point: Move element when scan, put zeros after dest pointer.
http://www.geeksforgeeks.org/move-zeroes-end-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 Can be improved to avoid unnecessary assignement
// 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;
}
http://comproguide.blogspot.com/2013/10/moving-zeroes-to-end-of-array.htmlvoid move_zeroes(int a[], int size){int i, dest = 0;for(i =0; i<size; i++){if(a[i] != 0){a[dest++] = a[i];}}for(i= dest; i<size; i++){a[i] = 0;}printf("\n");for(i= 0; i<size; i++){printf("%d ", a[i]);}}
The algorithm is simple, we take two indices , one to loop through the entire array, and another to keep track of the non-zero elements. Once we loop through all the elements, we can fill the remaining spaces with zeros.
Read full article from Algorithms and Me: Arrays : Move all zeros at the end of the arraypublic static void moveZerosToEnd(int[] array){int resInd = 0;// to keep track of non-zero elements in the final arrayint i;for( i = 0; i < array.length; i++ ){if( array[i] > 0 ){if( i != resInd ) //Avoid self copyarray[resInd] = array[i];resInd++;}}//Fill the remaining entries with 0while( resInd < array.length ){array[resInd] = 0;resInd++;}}