Sunday, August 16, 2015

Move zeroes (0's) to the end of array list

In a arraylist if you have zeroes (0's) at any randon location and want to move all the zeroes to the end of the list keeping the sequence of the list as-is, here is the solution -

Input - 1 9 8 4 0 0 2 7 0 6 0 9

Output - 1 9 8 4 2 7 6 9 0 0 0 0

void puchEnd()
{
   int count = 0;

   //Traverse the list and if element is non-zero, write to the list.
   for(int i=0 ; i<arr.length; i++)
  {
      if(arr[i].equals("0"))
      {
          //do nothing
      }
      else
      {
          arr[count++] = arr[i]; 
      }
  }
  
   //After writing all non-zero elements, now copy zero till the end of list.
   while(count < n)
   {
      arr[count++] = arr[i];
   }
}

No comments:

Post a Comment

Home