Move Zeros to the end of the list while keeping the order Algo

By   Tewodros   Date Posted: Sep. 27, 2021  Hits: 963   Category:  Algorithm   Total Comment: 0             A+ A-


side

Move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Example: Given A = {1,0,0,2,5,6,6,0,3,0}

Answer = {1,2,5,6,6,6,3,0,0,0,0}

Solution:

Here we would iterate through the list and we shift numbers to the left while counting how many zeros we have in the list. The shift happens  only if the number is non-zero number.

Here we will have one runner j that gets incremented only if we don't see zero. At the end this runner(index) will be behind by the number of zeros.

Once we reached the end, we exit and started a new loop that will we will put as many zero we counted at the end using the count of zeros we did in the first loop and the runner j.

 

            int countZeros = 0;

           int j = 0;

           for (int i = 0; i < A.Length; i++)   {

               if (A[i] == 0)  {

                   countZeros++;

               }

               else   {

                   A[j] = A[i];

                   j++;

               }

           }

           for (int i = j; i < A.Length; i++)  {

               A[i] = 0;

           }

           return A;

 

 


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* bidxch

Back to Top