-
Notifications
You must be signed in to change notification settings - Fork 0
/
apr18.cpp
53 lines (46 loc) · 1.03 KB
/
apr18.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
/*
Dutch National Flag Problem
This problem is named the "Dutch national flag problem" because the flag of the Netherlands is comprised of the colors red, white, and blue in separate parts. Although we won't be using colors, the premise of the challenge is to develop a sorting algorithm that does some form of separating of three kinds of elements.
Given an array consisting of only 0s, 1s, and 2s, sort the elements in linear time and constant space.
const arr = [2, 0, 1, 0, 2]
dutchNatFlag(arr)
// [0, 0, 1, 2, 2]
*/
#include <iostream>
using namespace std;
void swap(int arr[], int n, int m)
{
int t = arr[n];
arr[n] = arr[m];
arr[m] = t;
}
void dutchNatFlag(int arr[],int n)
{
int low=0, mid =0, high=n-1;
while(mid <= high)
{
if(arr[mid] == 0)
{
swap(arr, mid,low);
mid++;
low++;
}
else if (arr[mid] == 1)
mid++;
else
{
swap(arr,mid,high);
mid++;
high--;
}
}
}
int main()
{
int arr[] = {2,0,1,0,2};
dutchNatFlag(arr, 5);
for(int i=0;i<5;i++)
cout<<arr[i]<<" ";
cout<<endl;
return -1;
}