From adaf66ebb69147d03ef87e7d99995f56db52b8f0 Mon Sep 17 00:00:00 2001 From: Samruddhi Ghodake <72791227+samughodake@users.noreply.github.com> Date: Mon, 27 Sep 2021 18:04:15 +0530 Subject: [PATCH] chore(CPlusPlus): added segregation 0 and 1 (#486) --- .../CPlusPlus/Arrays/segregate-0-and-1.cpp | 61 +++++++++++++++++++ algorithms/CPlusPlus/README.md | 3 +- 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 algorithms/CPlusPlus/Arrays/segregate-0-and-1.cpp diff --git a/algorithms/CPlusPlus/Arrays/segregate-0-and-1.cpp b/algorithms/CPlusPlus/Arrays/segregate-0-and-1.cpp new file mode 100644 index 00000000..113f8597 --- /dev/null +++ b/algorithms/CPlusPlus/Arrays/segregate-0-and-1.cpp @@ -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 +#include +using namespace std; + +void segregate0and1(vector &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 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] << " "; + } +} diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index fe90ab66..1b7052cf 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -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