Move all zeros to start and ones to end in an Array of random integers in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that moves all zeroes to front and ones to end of the array.

Let's see the steps to solve the problem.

  • Initialise the array.

  • Initialise an index to 1.

  • Iterate over the given array.

    • If the current element is not zero, then update the value at the index with the current element.

    • Increment the index.

  • Write a loop that iterates from the above index to n

    • Update all the elements to 1.

  • Similarly, do for 0. Instead of increasing the index, decrease it to move all zeroes to front of the array.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void update1And0Positions(int arr[], int n) {
   int index = 0;
   for (int i = 0; i < n; i++) {
      if (arr[i] != 1) {
         arr[index++] = arr[i];
      }
   }
   while (index < n) {
      arr[index++] = 1;
   }
   index = 0;
   for (int i = n - 1; i >= 0; i--) {
      if (arr[i] == 1) {
         continue;
      }
      if (!index) {
         index = i;
      }
      if (arr[i] != 0) {
         arr[index--] = arr[i];
      }
   }
   while (index >= 0) {
      arr[index--] = 0;
   }
}
int main() {
   int arr[] = { 4, 5, 1, 1, 0, 0, 2, 0, 3, 1, 0, 1 };
   int n = 12;
   update1And0Positions(arr, n);
   for (int i = 0; i < n; i++) {
      cout << arr[i] << " ";
   }
   cout << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

0 0 0 0 4 5 2 3 1 1 1 1

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 01-Jul-2021 06:36:50
Advertisements