forked from manishaparuthi/manisha_cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsegregating.cpp
80 lines (69 loc) · 1.12 KB
/
segregating.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using namespace std;
#include<iostream>
void segregate(int [],int );
void segregate0n1(int [],int );
void print_array(int[],int);
int main()
{
int array[]={1,0,0,1,0,1,0};
int array1[]={1,1,1,1,1,1,0,0,0,0};
print_array(array,7);
cout<<endl;
print_array(array1,10);
segregate(array,7);
cout <<endl;
segregate0n1(array1,10);
print_array(array,7);
print_array(array1,10);
return 0;
}
void print_array(int array[],int size)
{
cout<<"The elements of array are:";
for(int i=0;i<size;i++)
{
cout<<array[i]<<" ";
}
}
void segregate(int array[],int size)
{
int count=0;
for (int i=0;i<size;i++)
{
if(array[i]==0)
{
count++;
}
}
for (int i=0;i<count;i++)
{
array[i]=0;
}
for (int i=count;i<size;i++)
{
array[i]=1;
}
}
void segregate0n1(int array[],int size)
{
int left=0;
int right=size-1;
while(left<right)
{
while(array[left]==0 && left<right)
{
left++;
}
while(array[right]==1 && left<right)
{
right--;
}
if(left<right)
{
array[left]=0;
array[right]=1;
left++;
right--;
}
}
}