From 655bf87436e0df84866493fd7dc17cb1603b3168 Mon Sep 17 00:00:00 2001 From: Ritish Sehgal <59483233+apex-blaze@users.noreply.github.com> Date: Sun, 28 Feb 2021 20:17:57 +0700 Subject: [PATCH] Added Dutch Flag algo (#87) --- arrays/README.md | 1 + arrays/c-or-cpp/dutch-flag-algo.cpp | 53 +++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 arrays/c-or-cpp/dutch-flag-algo.cpp diff --git a/arrays/README.md b/arrays/README.md index e26e2c97..8419274a 100644 --- a/arrays/README.md +++ b/arrays/README.md @@ -3,6 +3,7 @@ ### C or C++ 1. [Counting Inversions](c-or-cpp/count-inversions.cpp) +2. [Dutch Flag Algo](c-or-cpp/dutch-flag-algo.cpp) ### Python diff --git a/arrays/c-or-cpp/dutch-flag-algo.cpp b/arrays/c-or-cpp/dutch-flag-algo.cpp new file mode 100644 index 00000000..2445aaf8 --- /dev/null +++ b/arrays/c-or-cpp/dutch-flag-algo.cpp @@ -0,0 +1,53 @@ +/* Dutch Flag Algo: To separate three different entities + e.g :- Sort 0s,1s and 2s in an array without using sorting algo + Complexity : O(n) +*/ + +#include +using namespace std; + +/* 0 0 0 1 1 1 ? ? ? ? 2 2 2 + | | | + v v v + Low Mid High + + > In this algo, we tend to shrink this '?' region + whose ends are pointed by Mid and High indexes. + + > Low points to the region where the 1s start + +*/ + +void dutch_flag(int arr[],int size){ + //mid to high is the region we are about to shrink + int low = 0, mid = 0, high = size-1; + while(mid <= high){ + if(arr[mid] == 0){ + swap(arr[low],arr[mid]); + low++; mid++; + } + else if(arr[mid] == 1){ + mid++; + } + else if(arr[mid] == 2){ + swap(arr[high],arr[mid]); + high--; + } + } +} + +//Utility function to print the array +void printArray(int arr[], int arr_size) +{ + for (int i = 0; i < arr_size; i++) + cout << arr[i] << " "; +} + + +int main(){ + int a[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; + int n = sizeof(a)/sizeof(a[0]); + dutch_flag(a,n); + printArray(a,n); + return 0; +}