Skip to content

Commit e508f67

Browse files
committed
Segregating 0s and 1s
1 parent 386bbd8 commit e508f67

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

segregate_0_1.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
void segregate0and1(int a[], int n)
5+
{
6+
int x = 0;
7+
int y = n-1;
8+
while(x < y)
9+
{
10+
if(a[x] == 1)
11+
{
12+
swap(a[x], a[y]);
13+
y -= 1;
14+
}
15+
else
16+
x += 1;
17+
}
18+
}
19+
20+
void swap(int &i, int &j)
21+
{
22+
i = i+j;
23+
j = i-j;
24+
i = i-j;
25+
}
26+
int main()
27+
{
28+
int n, a[100];
29+
cout<<"Enter the size of the array: ";
30+
cin>>n;
31+
cout<<"Enter the elements of the array: ";
32+
for(int i=0;i<n;i++)
33+
cin>>a[i];
34+
segregate0and1(a, n);
35+
cout<<"The segregated array is:"<<endl;
36+
for (int i=0; i<n; i++)
37+
cout << a[i] << " ";
38+
return 0;
39+
}

0 commit comments

Comments
 (0)