Move All Zeros present in the array to the end

Given an array with n elements, move all of zeros present in the array to the end.

Example Input: 4 0 1 2 7 9 0 0 3
Expected Output: 4 2 7 9 3 0 0 0

We can easily solve this method by using a method similar to Quick Sort Partitioning

The idea is to keep on swapping the non-zero elements with the first available position from the start, at the end all the non zero numbers would come to the first.

Solution Implementation

#include <bits/stdc++.h>
using namespace std;

int swap(vector<int>& vec, int first, int second) {
    int temp = vec[first];
    vec[first] = vec[second];
    vec[second] = temp;
}

int main() {
    vector<int> vec = {4, 0, 1, 2, 7, 9, 0, 0, 3};
    int i = -1;
    for(int j = 0; j < vec.size(); j++) {
        if (vec[j] != 0) {
            i++;
            swap(vec, i, j);
        }
    }

    for(int i = 0; i < vec.size(); i++) {
        cout << vec[i] << " ";
    }
    cout << "\n";
}

 

Scroll to Top