Question:
How to move all zeroes in an array to the end? C++

Summary:

Suppose, we have an array of n positive integers. We must use this code to move every zero in the provided array to the right end of the array while preserving the non-zero elements' order. 


Solution:

//User function template for C++

class Solution{

public:

void pushZerosToEnd(int arr[], int n) {

    // code here

    int j=0,temp;

    for(int i=0;i<n;i++)

    {

            if(arr[i]!=0)

               {

                     temp=arr[i];

                     arr[i]=arr[j];

                     arr[j]=temp;

                     j++;

                }

         }

}

};



Explanation:

  1. The pushZerosToEnd method takes two parameters: arr[], representing the integer array, and n, representing the size of the array.

  2. It initializes an integer variable j to keep track of the position where non-zero elements will be placed initially. This variable starts at 0.

  3. The method iterates through the array using a for loop with index i ranging from 0 to n-1.

  4. Inside the loop, it checks if the current element arr[i] is not equal to zero.

  5. If arr[i] is non-zero, it swaps arr[i] with arr[j], effectively moving the non-zero element to the position indicated by j.

  6. It then increments j to prepare for the next non-zero element.

  7. This process continues until all elements in the array have been processed.

  8. As a result, all non-zero elements are shifted to the beginning of the array, and all zero elements are pushed to the end, maintaining the relative order of non-zero elements.

  9. The method completes, and the array arr[] is modified in place, with zeros pushed to the end while preserving the order of non-zero elements.

  10. The class Solution encapsulates this functionality, allowing users to push zeros to the end of an integer array using the pushZerosToEnd method.


Answered by: >rakshay7349

Credit: >GeekforGeeks


Suggested blogs:

>Python Error Solved: load_associated_files do not load a txt file

>Python Error Solved: pg_config executable not found

>Set up Node.js & connect to a MongoDB Database Using Node.js

>Setting up a Cloud Composer environment: Step-by-step guide

>What is microservice architecture, and why is it better than monolithic architecture?

>What is pipe in Angular?

>What makes Python 'flow' with HTML nicely as compared to PHP?

>What to do when MQTT terminates an infinite loop while subscribing to a topic in Python?

>Creating custom required rule - Laravel validation

>How to configure transfers for different accounts in stripe with laravel?


Submit
0 Answers