-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuicksort using the Dutch national flag algorithm.cpp
More file actions
63 lines (61 loc) · 1.25 KB
/
Quicksort using the Dutch national flag algorithm.cpp
File metadata and controls
63 lines (61 loc) · 1.25 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
#include <bits/stdc++.h>
using namespace std;
pair<int,int>part(int lo,int hi,vector<int>&arr)
{
int pivot=arr[hi];
int mid=lo;
while(mid<=hi)
{
if(arr[mid]<pivot){
swap(arr[mid],arr[lo]);
lo++;
mid++;
}
else if(arr[mid]>pivot){
swap(arr[mid],arr[hi]);
hi--;
}
else{
mid++;
}
}
return make_pair(lo-1,mid);
}
void quicksort(int lo,int hi,vector<int>&arr)
{
if(lo>=hi)return;
if(hi-lo==1){
if(arr[lo]>arr[hi]){
swap(arr[lo],arr[hi]);
}
return;
}
pair<int,int>pi=part(lo,hi,arr);
quicksort(lo,pi.first,arr);
quicksort(pi.second,hi,arr);
}
vector<int> quickSortUsingDutchNationalFlag(vector<int> &arr)
{
// Write your code here.
int lo=0,hi=arr.size()-1;
quicksort(lo,hi,arr);
return arr;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
vector<int>v(n);
for(int i=0;i<n;i++)cin>>v[i];
vector<int>ans= quickSortUsingDutchNationalFlag(v);
for(int i=0;i<n;i++)
{
cout<<ans[i]<<" ";
}
cout<<endl;
}
}