Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added code to Segregate 0s and 1s in an array.cpp #46

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions Code to Segregate 0s and 1s in an array.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// C++ code to Segregate 0s and 1s in an array
#include <bits/stdc++.h>
using namespace std;

// Function to segregate 0s and 1s
void segregate0and1(int arr[], int n)
{
int count = 0; // Counts the no of zeros in arr

for (int i = 0; i < n; i++) {
if (arr[i] == 0)
count++;
}

// Loop fills the arr with 0 until count
for (int i = 0; i < count; i++)
arr[i] = 0;

// Loop fills remaining arr space with 1
for (int i = count; i < n; i++)
arr[i] = 1;
}

// Function to print segregated array
void print(int arr[], int n)
{
cout << "Array after segregation is ";

for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}

// Driver function
int main()
{
int arr[] = { 0, 1, 0, 1, 1, 1 };
int n = sizeof(arr) / sizeof(arr[0]);

segregate0and1(arr, n);
print(arr, n);

return 0;
}