forked from sukritishah15/DS-Algo-Point
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDutchFlag.c
53 lines (46 loc) · 941 Bytes
/
DutchFlag.c
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
#include <stdio.h>
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void DutchFlag(int a[], int n)
{
// sample input : 0 1 0 2 0
// sample outpu : 0 0 0 1 2
// Time complexity O(nlog(n))
// Space complexity O(n)
int l = 0;
int h = n - 1;
int m = 0;
while (m <= h) {
switch (a[m]) {
case 0:
swap(&a[l++], &a[m++]);
break;
case 1:
m++;
break;
case 2:
swap(&a[m], &a[h--]);
break;
}
}
}
int main()
{ int n;
scanf("%d",&n);
int a[n] ;
for(int i = 0 ; i<n ;i++)
scanf("%d",&a[i]);
DutchFlag(a,n);
for(int i = 0 ; i<n ;i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}
// sample input : 0 1 0 2 0
// sample outpu : 0 0 0 1 2
// Time complexity O(nlog(n))
// Space complexity O(n)