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

By   Tewodros   Date Posted: Sep. 27, 2021  Hits: 986   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 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 count j is behind .

Once we reached the end, we exit and started a new loop that we will put as many zeros we counted at the end starting from j.

 

            

           int j = 0;

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

               if (A[i] ! = 0)   {

                   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:* vvpswt

Back to Top