diff --git a/arrays/README.md b/arrays/README.md index 2bf2b625..598a00ca 100644 --- a/arrays/README.md +++ b/arrays/README.md @@ -5,6 +5,7 @@ 1. [Counting Inversions](c-or-cpp/count-inversions.cpp) 2. [Dutch Flag Algo](c-or-cpp/dutch-flag-algo.cpp) 3. [Left Rotation of Array](c-or-cpp/left-rotation.cpp) +4. [Shift Negatives in Array](c-or-cpp/shift-negatives.cpp) ### Python @@ -17,3 +18,4 @@ ### Java 1. [Counting Inversions](java/count-inversions.java) + diff --git a/arrays/c-or-cpp/shift-negatives.cpp b/arrays/c-or-cpp/shift-negatives.cpp new file mode 100644 index 00000000..f2d2a81b --- /dev/null +++ b/arrays/c-or-cpp/shift-negatives.cpp @@ -0,0 +1,52 @@ +#include +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 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