Here the question is to put all the zeroes to the end of the array.
I’ve written the below code, but after passing {arr,n} to the pushzero() function, when I try to print the array, it does nothing, and the value of n changes to zero after calling the pushzero() function.
#include <bits/stdc++.h>
using namespace std;
void pushzero(int arr[], int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < i + 1; j++) {
if (arr[j] == 0) {
swap(arr[j+1], arr[j]);
}
}
}
}
int main() {
int arr[] = { 2, 6, 0, 0, 1, 9, 0, 8, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < n; i++) {
cout << arr[i] << " " << "\n";
}
pushzero(arr, n);
for (int j = 0; j < n; j++) { // n is 0 here
cout << arr[j] << " ";
}
return 0;
}
>Solution :
You could do it by using 0 as a pivot element and whenever you see a non zero element you will swap it with the pivot element. So all the non zero element will come at the beginning.
void pushzero(int arr[], int n) {
int j =0;
for (int i = 0; i < n; i++) {
if(arr[i] != 0) {
swap(arr[i], arr[j]);
j++;
}
}
}
Demo: https://godbolt.org/z/oMdxfdWjG