-
Notifications
You must be signed in to change notification settings - Fork 0
/
quick_sortH.cpp
73 lines (61 loc) · 1.22 KB
/
quick_sortH.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
// partition using hoare's scheme
#include <Rcpp.h>
using namespace Rcpp;
class Special{
public:
int nswap;
int ncomp;
bool Less(int a, int b){
ncomp++;
return a < b;
}
void Swap(NumericVector arr, int i, int j){
nswap++;
std::swap(arr[i], arr[j]);
}
Special(){
nswap = 0;
ncomp = 0;
}
};
int partition(NumericVector a,int start,int end, Special& special)
{
int pivot = a[start];
int i = start - 1;
int j = end + 1;
//Rcout << a <<"\n";
while(1)
{
do {
i++;
} while (special.Less(a[i], pivot));
do {
j--;
} while (special.Less(pivot, a[j]));
if(i >= j)
return j;
special.Swap(a, i, j);
}
}
void qsort(NumericVector a,int start,int end, Special& special)
{
if(start < end)
{
int P_index = partition(a, start, end, special);
//Rcout << a <<"; swap: " << special.nswap << "; com: " << special.ncomp << "\n";
qsort(a, start, P_index, special);
qsort(a, P_index+1,end, special);
}
}
// [[Rcpp::export]]
NumericVector QuickSortH(NumericVector arr)
{
Special special;
int len = arr.size();
qsort(arr, 0, len-1, special);
NumericVector res(2);
res[0] = special.nswap;
res[1] = special.ncomp;
//Rcout << arr << "\n";
return res;
}