-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathDutchNationalFlagProb.cpp
More file actions
72 lines (52 loc) · 1.59 KB
/
DutchNationalFlagProb.cpp
File metadata and controls
72 lines (52 loc) · 1.59 KB
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
//The flag of the Netherlands consists of three colors: white, red, and blue.
//The task is to randomly arrange balls of white, red, and blue such that balls of the same color are placed together.
//For simplicity we assume the numbers 0,1,2 in the place of the colors white, red and blue.
//Therefore the array is assumed to have values in {0, 1, 2}
#include<iostream>
#include<stdio.h>
using namespace std;
// Function to sort the input array,
void DNFS(int arr[], int arr_size)
{
int low = 0;
int high = arr_size - 1;
int mid = 0;
// Iterate till all the elements are sorted
while (mid <= high)
{
switch (arr[mid])
{
// mid is 0
case 0:
swap(arr[low++], arr[mid++]);
break;
// mid is 1 .
case 1:
mid++;
break;
// mid is 2
case 2:
swap(arr[mid], arr[high--]);
break;
}
}
}
// Function to print array arr[]
void printArray(int arr[], int arr_size)
{
// Iterate and print every element
for (int i = 0; i < arr_size; i++)
cout << arr[i] << " ";
}
// Driver Code
int main()
{
int arr[] = {0,0,1,2,0,1,2};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Array before running the algorithm: ";
printArray(arr, n);
DNFS(arr, n);
cout << "\nArray after DNFS algorithm: ";
printArray(arr, n);
return 0;
}