Added Dutch Flag algo (#93)

pull/98/head
Ritish Sehgal 2021-03-04 00:25:50 +05:30 committed by GitHub
parent 6fe5b94526
commit cdaef8f9af
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 54 additions and 0 deletions

View File

@ -5,6 +5,7 @@
1. [Counting Inversions](c-or-cpp/count-inversions.cpp) 1. [Counting Inversions](c-or-cpp/count-inversions.cpp)
2. [Dutch Flag Algo](c-or-cpp/dutch-flag-algo.cpp) 2. [Dutch Flag Algo](c-or-cpp/dutch-flag-algo.cpp)
3. [Left Rotation of Array](c-or-cpp/left-rotation.cpp) 3. [Left Rotation of Array](c-or-cpp/left-rotation.cpp)
4. [Shift Negatives in Array](c-or-cpp/shift-negatives.cpp)
### Python ### Python
@ -17,3 +18,4 @@
### Java ### Java
1. [Counting Inversions](java/count-inversions.java) 1. [Counting Inversions](java/count-inversions.java)

View File

@ -0,0 +1,52 @@
#include<bits/stdc++.h>
using namespace std;
// Move all negative elements to left and positives to right side of the array
// Approach 1 --> Partition Algo - O(n)
void shiftNegatives_A(int arr[],int size){
int j = -1,pivot=0;
for(int i=0;i<size;++i){
if(arr[i]<pivot){
j++;
swap(arr[i],arr[j]);
}
}
}
// Approach 2 --> Two-pointer Method - O(n)
void shiftNegatives_B(int arr[],int size){
int left = 0, right = size-1;
while(left < right){
if(arr[left]<0 && arr[right]<0){
left++;
}
else if(arr[left]>0 && arr[right]>0){
right--;
}
else if(arr[left]>0 && arr[right]<0){
swap(arr[left],arr[right]);
left++; right--;
}
else{
left++; right--;
}
}
}
void printArray(int arr[],int size){
for(int i=0;i<size;++i){
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main()
{
int arr[] = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
// shiftNegatives_A(arr, n);
// shiftNegatives_B(arr, n);
printArray(arr, n);
return 0;
}