Skip to content

Commit

Permalink
Create sort01TwoPointer.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
GhostRider987 authored Oct 1, 2023
1 parent d29f7a1 commit 5e310c0
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions cpp/sort01TwoPointer.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#include <iostream>
#include <vector>
using namespace std;

void sortZeroesAndOnes(vector<int> &v)
{
int left_ptr = 0;
int right_ptr = v.size()-1;

while(left_ptr<right_ptr)
{
if(v[left_ptr]==1 && v[right_ptr]==0){
v[left_ptr++]=0;
v[right_ptr--]=1;
}

if(v[left_ptr]==0){
left_ptr++;
}

if(v[right_ptr]==1){
right_ptr--;
}
}
}

int main()
{
int n;
cin>>n;

vector<int> v;

for(int i=0; i<n; i++)
{
int ele;
cin>>ele;
v.push_back(ele);
}

sortZeroesAndOnes(v);

for(int i=0; i<n; i++)
{
cout<<v[i]<<" ";
}cout<<endl;
return 0;
}

0 comments on commit 5e310c0

Please sign in to comment.