-
Notifications
You must be signed in to change notification settings - Fork 114
/
Copy pathDNF_Sort.cpp
66 lines (51 loc) · 1.1 KB
/
DNF_Sort.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
// Name: JHALA DEVRAJSINH SHRIPALSINH
// Date: 01/07/2021
// Purpose: Dutch National Flag (DNF) Sort
// Approach:
// Check the value of arr[mid]:
// if 0, swap arr[low] and arr[mid], low++, mid++
// if 1, mid++
// if 2, swap arr[mid] and arr[high], high--
// Time complexity:
// O(N) because in each operation, either mid gets incremented or high gets decremented
#include<bits/stdc++.h>
using namespace std;
void swap(int arr[], int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void DNF_Sort(int arr[], int n)
{
int low = 0;
int mid = 0;
int high = n - 1;
while(mid <= high)
{
if(arr[mid] == 0)
{
swap(arr,low,mid);
low++; mid++;
}
else if(arr[mid] == 1)
{
mid++;
}
else
{
swap(arr,mid,high);
high--;
}
}
}
int main()
{
int arr[] = {1,0,2,1,0,1,2,1,2};
DNF_Sort(arr,9);
for(int i=0;i<9;i++)
{
cout << arr[i] << " ";
}
return 0;
}