-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqsort.h
88 lines (86 loc) · 1.32 KB
/
qsort.h
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#pragma once
namespace epicyclism
{
template<typename I> constexpr void qsort(I b, I e)
{
auto swap = [&](I l, I r)
{
auto tmp = *l;
*l = *r;
*r = tmp;
};
auto partition = [&](I l, I r)
{
--r;
auto v = *r;
auto i = l;
while (l < r)
{
if (*l < v)
{
swap(i, l);
++i;
}
++l;
}
swap(i, r);
return i;
};
if (b < e)
{
I sp = partition(b, e);
// minimise max stack depth by recursing on smaller partition first
if ((sp - b) < (e - sp + 1))
{
qsort(b, sp);
qsort(sp + 1, e);
}
else
{
qsort(sp + 1, e);
qsort(b, sp);
}
}
}
template<typename I, typename F> constexpr void qsort(I b, I e, F f)
{
auto swap = [&](I l, I r)
{
auto tmp = *l;
*l = *r;
*r = tmp;
};
auto partition = [&](I l, I r)
{
--r;
auto v = *r;
auto i = l;
while (l < r)
{
if (f(*l, v))
{
swap(i, l);
++i;
}
++l;
}
swap(i, r);
return i;
};
if (b < e)
{
I sp = partition(b, e);
// minimise max stack depth by recursing on smaller partition first
if ((sp - b) < (e - sp + 1))
{
qsort(b, sp, f);
qsort(sp + 1, e, f);
}
else
{
qsort(sp + 1, e, f);
qsort(b, sp, f);
}
}
}
}