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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
|
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#ifndef BASE_TL_ALGORITHM_H
#define BASE_TL_ALGORITHM_H
#include "range.h"
/*
insert 4
v
1 2 3 4 5 6
*/
template<class R, class T>
R partition_linear(R range, T value)
{
concept_empty::check(range);
concept_forwarditeration::check(range);
concept_sorted::check(range);
for(; !range.empty(); range.pop_front())
{
if(!(range.front() < value))
return range;
}
return range;
}
template<class R, class T>
R partition_binary(R range, T value)
{
concept_empty::check(range);
concept_index::check(range);
concept_size::check(range);
concept_slice::check(range);
concept_sorted::check(range);
if(range.empty())
return range;
if(range.back() < value)
return R();
while(range.size() > 1)
{
unsigned pivot = (range.size()-1)/2;
if(range.index(pivot) < value)
range = range.slice(pivot+1, range.size()-1);
else
range = range.slice(0, pivot+1);
}
return range;
}
template<class R, class T>
R find_linear(R range, T value)
{
concept_empty::check(range);
concept_forwarditeration::check(range);
for(; !range.empty(); range.pop_front())
if(value == range.front())
break;
return range;
}
template<class R, class T>
R find_binary(R range, T value)
{
range = partition_linear(range, value);
if(range.empty()) return range;
if(range.front() == value) return range;
return R();
}
template<class R>
void sort_bubble(R range)
{
concept_empty::check(range);
concept_forwarditeration::check(range);
concept_backwarditeration::check(range);
// slow bubblesort :/
for(; !range.empty(); range.pop_back())
{
R section = range;
typename R::type *prev = §ion.front();
section.pop_front();
for(; !section.empty(); section.pop_front())
{
typename R::type *cur = §ion.front();
if(*cur < *prev)
swap(*cur, *prev);
prev = cur;
}
}
}
/*
template<class R>
void sort_quick(R range)
{
concept_index::check(range);
}*/
template<class R>
void sort(R range)
{
sort_bubble(range);
}
template<class R>
bool sort_verify(R range)
{
concept_empty::check(range);
concept_forwarditeration::check(range);
typename R::type *prev = &range.front();
range.pop_front();
for(; !range.empty(); range.pop_front())
{
typename R::type *cur = &range.front();
if(*cur < *prev)
return false;
prev = cur;
}
return true;
}
#endif // TL_FILE_ALGORITHMS_HPP
|