forked from sunnyshahabuddin/Coding-Ninjas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsegregate.cpp
More file actions
52 lines (43 loc) · 935 Bytes
/
segregate.cpp
File metadata and controls
52 lines (43 loc) · 935 Bytes
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
#include <iostream>
using namespace std;
/* Function to swap *a and *b */
void swap(int *a, int *b);
void segregateEvenOdd(int arr[], int size)
{
/* Initialize left and right indexes */
int left = 0, right = size-1;
while (left < right)
{
/* Increment left index while we see 0 at left */
while (arr[left] % 2 == 0 && left < right)
left++;
/* Decrement right index while we see 1 at right */
while (arr[right] % 2 == 1 && left < right)
right--;
if (left < right)
{
/* Swap arr[left] and arr[right]*/
swap(&arr[left], &arr[right]);
left++;
right--;
}
}
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
/* Driver code */
int main()
{
int arr[] = {12, 34, 45, 9, 8, 90, 3};
int arr_size = sizeof(arr)/sizeof(arr[0]);
int i = 0;
segregateEvenOdd(arr, arr_size);
cout <<"Array after segregation ";
for (i = 0; i < arr_size; i++)
cout << arr[i] << " ";
return 0;
}