-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdutch_national_flag.cpp
99 lines (80 loc) · 1.99 KB
/
dutch_national_flag.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/****************************************************************************
File name: dutch_national_flag.cpp
Author: babajr
*****************************************************************************/
/*
Given an array containing 0s, 1s and 2s, sort the array in-place.
You should treat numbers of the array as objects,
hence, we can’t count 0s, 1s, and 2s to recreate the array.
Input: [1, 0, 2, 1, 0]
Output: [0 0 1 1 2]
*/
#include<bits/stdc++.h>
using namespace std;
/*
Helper API to swap the two elements in an array.
*/
void swap(int arr[], int idx1, int idx2)
{
int temp = arr[idx1];
arr[idx1] = arr[idx2];
arr[idx2] = temp;
}
/*
Two Pointer Approach.
Algo:
--> Use two pointers i.e. low and high. low is pointing to first and high is pointing
to last element.
--> move all zeros to left of low and all twos after high.
--> all ones will remain between low and high.
*/
void sort_dutch_national_flag(int arr[], int size)
{
// 0 0 0 1 1 1 1 2 2 2
// low high
// all elements < low are 0.
// all elements > high are 2.
// all elements from >= low to i are 1.
int low = 0, high = size - 1;
// traverse the array.
int i = 0;
while(i <= high)
{
if(arr[i] == 0) // move 0's to left of low.
{
swap(arr, i, low);
i++;
low++;
}
else if(arr[i] == 1)
{
i++;
}
else // if(arr[i] == 2)
{
swap(arr, i, high); // move 2's to right of high.
high--;
}
}
}
/*
Helper API to print the array.
*/
void print_array(int arr[], int size)
{
for(int i = 0; i < size; i++)
{
printf("%d\t", arr[i]);
}
printf("\n");
}
int main(void)
{
int arr[] = {1, 2, 2, 0, 0, 2, 1, 0};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Original Array\n");
print_array(arr, size);
sort_dutch_national_flag(arr, size);
print_array(arr, size);
return 0;
}