How to push all zeroes to the end of the array in C++
In this tutorial, we will learn to push all zeroes to the end of an array in C++. As we have given an array and we have to shift zeroes to the end of the array.
For Example:
- Given array= {1,0, 5, 7. 0, 12, 0,4, 0, 8}
- Push all zeroes to the end of the array.
- Output: {1, 5, 7, 12, 4, 8, 0, 0, 0 , 0}
Also, there are many ways to solve this given problem. But, we will use the most efficient of them.
Approach:
- Firstly, count the non-zero element.
- Now, traverse through the array element one by one.
- If the element is non-zero, then replace it with the element whose index is ‘count_non_zero’.
- In this process, here we will increase the count_non_zero.
- Finally, if count_on_zero is less than the total number of the element then, put 0 to the remaining indexes.
- The time complexity of this method: O(n) where n is the total number of elements in the array.
- Auxiliary Space: O(1)
You may also like:
How to remove or eliminate the extra spaces from a given string in C++
Push all zeroes to the end of the array in C++
You can see the implementation of the above approach here.
// A C++ program to shift zeroes at the end
#include <iostream>
using namespace std;
// Function to shift zeroes
void movezeroes(int arr[], int pu)
{
int count_non_zero = 0;
// traverse through the array, and if the element is non zero then,
//replace with the element.
for (int i = 0; i < pu; i++)
if (arr[i] != 0)
arr[count_non_zero++] = arr[i]; //increment the count
// check if count of non zero elements is less than total number
//of elements, then put zero to the remaining indexes.
while (count_non_zero < pu)
arr[count_non_zero++] = 0;
}
int main()
{
int arr[] = {1, 8, 0, 2, 0, 0, 2, 1, 0, 0, 0, 9};
int pu = sizeof(arr) / sizeof(arr[0]);
movezeroes(arr, pu);
cout << "Array after shifting"<<endl ;
for (int i = 0; i < pu; i++)
cout << arr[i] << " ";
return 0;
}
Output Explanation:
INPUT: {1, 8, 0, 2, 0, 0, 2, 1, 0, 0, 0, 9}
OUTPUT: {1, 8, 2, 2, 1, 9, 0, 0, 0, 0, 0, 0}
Leave a Reply