chore(CPlusPlus): added segregation 0 and 1 (#486)

pull/498/head
Samruddhi Ghodake 2021-09-27 18:04:15 +05:30 committed by GitHub
parent 9d673a8cd1
commit adaf66ebb6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 63 additions and 1 deletions

View File

@ -0,0 +1,61 @@
/*
Description: A program to segregate the array of 0s and 1s
Approach: Counting the number of 0s present in the array and
saving it in variable z. For the first z indexes, putting 0 and
for the remaining indexes putting 1.
Time complexity: O(n)
*/
#include <iostream>
#include <vector>
using namespace std;
void segregate0and1(vector<int> &v, int n)
{
int z = 0;
for (int i = 0; i < n; i++)
{
//counting the number of 0s and storing it the variable z
if (v[i] == 0)
{
z++;
}
}
//for z indexes, putting 0 in the vector
//for remaining indexes putting 1 in the vector
for (int j = 0; j < n; j++)
{
if (j < z)
{
v[j] = 0;
}
else
{
v[j] = 1;
}
}
}
int main()
{
int n;
cout << "Enter number of array elements\n";
cin >> n;
vector<int> v(n);
cout << "Enter the array elements (only 0 and 1)\n";
for (int i = 0; i < n; i++)
{
cin >> v[i];
}
//calling the function
segregate0and1(v, n);
cout << "After segregating, the array is: \n";
for (int j = 0; j < n; j++)
{
cout << v[j] << " ";
}
}

View File

@ -16,7 +16,8 @@
12. [Leaders In The Array](Arrays/leaders-in-array.cpp)
13. [Elements appear thrice In The Array](Arrays/Elements_appears_thrice.cpp)
14. [Maximum Difference](Arrays/maximum-difference.cpp)
15. [Occurrence of one in sorted array](algorithms/CPlusPlus/Arrays/occurence-of-one-in-sorted-array.cpp)
15. [Occurrence of one in sorted array](Arrays/occurence-of-one-in-sorted-array.cpp)
16. [Segregate 0s and 1s](Arrays/segregate-0-and-1.cpp)
## Dynamic-Programming