From c4a369243740499722fe32b7aaea2e23dfdad40d Mon Sep 17 00:00:00 2001 From: Gitansh Kapoor <72307552+GitanshKapoor@users.noreply.github.com> Date: Fri, 1 Oct 2021 01:32:01 +0530 Subject: [PATCH] Create Sort_Array 0 1.cpp --- Sort_Array 0 1.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Sort_Array 0 1.cpp diff --git a/Sort_Array 0 1.cpp b/Sort_Array 0 1.cpp new file mode 100644 index 0000000..53c05ae --- /dev/null +++ b/Sort_Array 0 1.cpp @@ -0,0 +1,41 @@ +// C++ program to sort a +// binary array in one pass +#include +using namespace std; + +/*Function to put all 0s on +left and all 1s on right*/ +void segregate0and1(int arr[], + int size) +{ + int type0 = 0; + int type1 = size - 1; + + while(type0 < type1) + { + if(arr[type0] == 1) + { + swap(arr[type0], + arr[type1]); + type1--; + } + else + type0++; + } +} + +// Driver Code +int main() +{ + int arr[] = {0, 1, 0, 1, 1, 1}; + int i, arr_size = sizeof(arr) / + sizeof(arr[0]); + + segregate0and1(arr, arr_size); + + cout << "Array after segregation is "; + for (i = 0; i < arr_size; i++) + cout << arr[i] << " "; + + return 0; +}