Monday, April 20, 2015

SAP Labs Question: Move all zeroes to end of array

Problem: Given an array of integers, move all the zero’s in a given array to the end of the array. The order of all other elements should remain same.

Implementation:

void moveZeros(int *arr, int len)
{
if(arr == NULL || len == 0 || len == 1)
return;
int count = 0;
for(int i = 0; i < len; ++i)
{
if(arr[i] != 0)
arr[count++] = arr[i];
}
while(count < len)
arr[count++] = 0;
}

Complexity: O(n)

No comments:

Post a Comment