-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path07_min_range.html
357 lines (294 loc) · 12.3 KB
/
07_min_range.html
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>7. Minimum selection on ranges</title>
<link rel="stylesheet" href="template/style.css">
</head>
<body>
<span style="float: right">
[
<a href="06_min_max.html">previous</a>,
<a href="index.html">contents</a>,
<a href="08_lisp.html">next</a>
]
</span>
<a name="L7.-Minimum-selection-on-ranges"></a>
<h1>7. Minimum selection on ranges</h1>
<a name="The-standard-is-not-a-limitation-on-ideas"></a>
<h2>The standard is not a limitation on ideas</h2>
<p>When I joined A9 I wrote a little generic function and it was not using STL iterators.
It used some other iterator like thing, but, totally different.
We wrote it, tested it, sent it in and one of
the wise people who works for us looked at it and sent back
the reply, “you guys have to learn about STL iterators”,
which I really appreciate.
In Silicon Valley you have to be careful about saying you’re
an expert. You might be talking to the guy who invented it.</p>
<p>That guy’s attitude is that if
there is something in the standard, that’s the only thing you should use.
This is false.
Use STL only when it fits.
If you come up with some other idea (many ideas in the world)
try it.</p>
<a name="Minimum-element-in-a-range"></a>
<h2>Minimum element in a range</h2>
<p>Now we want to apply <code>min</code> to a range.
Suppose we want to find an item with smallest price.
We need an interface which allows us to take as many items as you like and find the minimum.
In STL it’s called <a href="https://en.cppreference.com/w/cpp/algorithm/min_element"><code>std::min_element</code></a></p>
<p>The algorithm is very simple, but there are details we need
to learn about ranges.
We will show an implementation and then talk about it:</p>
<pre><code>template <typename I, typename Compare>
// I is a ForwardIterator
// Compare is StrictWeakOrdering on ValueType(I)
I min_element(I first, I last, Compare cmp) {
if (first == last) {
return last;
}
I min_el = first;
++first;
while (first != last) {
if (cmp(*first, *min_el)) {
min_el = first;
}
++first;
}
return min_el;
}
</code></pre>
<a name="Iterator-conventions"></a>
<h3>Iterator conventions</h3>
<p>We need to talk about iterator conventions.
Notice that <code>min_element</code> doesn’t return the value itself,
but the iterator pointing to the minimum element.
Why?
Because we probably want to update the value.</p>
<p>Suppose I’m a manager and I want to look for the
worst-performing guy and then fire him (joke).
I don’t want his value, I want a handle on him.
I want an iterator.
Do you see my point?
You very often want to do
things with what you find.</p>
<p>There is another reason.
The range might be empty<sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup>.
In which case we return the last iterator.</p>
<p><code>first</code> and <code>last</code> are maybe bad names, but that’s what they are.
They are hard to change, because I called them that everywhere.
<code>last</code> actually doesn’t mean last.
<code>last</code> means one after the last element<sup id="fnref:2"><a href="#fn:2" rel="footnote">2</a></sup>.
In order to define a sequence you need to point past the last.
Because you want to able to work with empty ranges.</p>
<pre><code> a b c d
first ^
last ^
</code></pre>
<p>Suppose <code>last</code> is actually last and you point to the same place.
That indicates a range of one element.
There is no way to do zero.</p>
<p>Later, we will look at algorithms for partitioning.
We want to partition good people from bad people.
After the partition we will return a pointer which separates good from bad.
There will be first, last, and middle.
The middle partitions between
the first bad and first good.
But there may be no good, or no bad elements.
We need to able to return an empty range.</p>
<p>In C++ this is a standard convention. Some
people in the world of Java and Python are slowly realizing that maybe it
has something to do with mathematics and not with C++.
But it will take decades before people fully realize that you have to always go
past the end.
Mathematically you need <a href="https://mathworld.wolfram.com/Half-ClosedInterval.html">semi-open intervals</a>.
They are denoted like so:</p>
<pre><code>[i, j)
</code></pre>
<p>Or in our terms:</p>
<pre><code>[first, last)
</code></pre>
<a name="Forward-iterator"></a>
<h3>Forward iterator</h3>
<p>What kind of thing is <code>I</code>.
We indicated it was a <code>ForwardIterator</code>.
There is also <code>InputIterator</code>.
Both are for iterating forward,
as opposed to random jumps.
What is an <code>InputIterator</code>?
Input iterators describe algorithms
which go through the river once<sup id="fnref:3"><a href="#fn:3" rel="footnote">3</a></sup>.
It’s like they’re reading stuff from the wire<sup id="fnref:4"><a href="#fn:4" rel="footnote">4</a></sup>.
Imagine the various kinds of streams<sup id="fnref:5"><a href="#fn:5" rel="footnote">5</a></sup>.</p>
<p>But, in our algorithm we store a previous position in the variable <code>min_el</code>.
Therefore the things which go through the wire will not work.
So it must be a <code>ForwardIterator</code>.</p>
<a name="Finding-min-and-max-together"></a>
<h2>Finding min and max together</h2>
<p>How many comparisons do we need to find the min of five elements?
Four.
In general why do we need <code>n - 1</code> comparisons.
Why no more? We don’t need to compare an element with itself.
Why no fewer?
Maybe we could do it
in <code>n - 2</code> with a clever algorithm?
The simple argument to
remember is that <code>n - 1</code> guys have to lose.
We’re finding a winner in our competition.
If a person didn’t play in a competition, if he didn’t lose,
we cannot eliminate him.
We need to eliminate all but one.</p>
<p>How many comparisons if we need to find minimum and maximum together?
Obviously we could do <code>2n - 2</code>,
but what about fewer<sup id="fnref:6"><a href="#fn:6" rel="footnote">6</a></sup>?
The idea is very simple.
Assume that we worked up to the middle of
of our range and we have a running min and a running max.
The temptation is take the next element compare him with min and with max.
That’s very sad because very often we will do two comparisons and then discount the other.
So for one element we will be doing two comparisons.
The trick is to pick two new elements,
the next element, and the one after next.
We know nothing about them.
We compare them with one comparison.
Then we know that one of them is a potential min
and the other is a potential max.
Then we compare potential min with the current min
and potential max with current max.
So we need to do three comparisons for every pair, so roughly
speaking we need <code>3n/2</code>.</p>
<p>Let’s do it.
This can be a little bit tricky.
Do not start writing things from the beginning because
you don’t know what goes in the beginning.
Try to write code from the middle.
Try to write the body of the loop.
That’s where I described the algorithm
to start with.
Then go back and make the loop invariants on which we depend true.</p>
<pre><code>template <typename I, typename Compare>
// I is a ForwardIterator
// Compare is StrictWeakOrdering on ValueType(I)
std::pair<I, I> minmax_element(I first, I last, Compare cmp) {
if (first == last) {
return std::make_pair(last, last);
}
I min_el = first;
++first;
if (first == last) {
return std::make_pair(min_el, min_el);
}
I max_el = first;
I next = first;
++next;
if (cmp(*max_el, *min_el)) {
std::swap(min_el, max_el);
}
while (first != last && next != last) {
// min_el contains the current min
// max_el contains the current max
// next and first and the next pair of elements to examine
I potential_min = first;
I potential_max = next;
if (cmp(*potential_max, *potential_min)) {
std::swap(potential_max, potential_min);
}
if (cmp(*potential_min, *min_el)) {
min_el = potential_min;
}
if (!cmp(*potential_max, *max_el)) {
max_el = potential_max;
}
++next;
first = next;
++next;
}
if (first != last) {
// odd elements, one left over
if (cmp(*first, *min_el)) {
min_el = first;
// first < min_el <= max_el, so we don't need to check the next case
} else if (!cmp(*first, *max_el)) {
max_el = first;
}
}
return std::make_pair(min_el, max_el);
}
</code></pre>
<p>Example:</p>
<pre><code>int a[] = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 8, 7, 6, 2 };
size_t n = sizeof(a) / sizeof(int);
auto pair = minmax_element(a, a + n, std::less<int>());
</code></pre>
<p>This algorithm was invented by <a href="https://users.soe.ucsc.edu/~pohl/bio.htm">Ira Pohl</a> of UC Santa Cruz, in the mid-seventies<sup id="fnref:7"><a href="#fn:7" rel="footnote">7</a></sup>.
He also proved it was optimal.
It’s also practically good.
It was <a href="https://en.cppreference.com/w/cpp/algorithm/minmax_element">added to</a> the standard in C++11.</p>
<a name="Code"></a>
<h2>Code</h2>
<ul>
<li><a href="code/minmax_range.h">minmax_range.h</a></li>
<li><a href="code/test_minmax.cpp">test_minmax.cpp</a></li>
</ul>
<div class="footnotes">
<hr/>
<ol>
<li id="fn:1">
<p>Many languages struggle with empty ranges because they prefer their algorithms
to work with values instead of iterators.
For example, they might return <code>nil</code> or a boolean which indicates
whether the value was found or not, or they may throw an exception.</p>
<p>Of course, this adds a few lines of code,
or the possibility that you forget to check for the nil case, and perhaps
restricts the algorithm to reference types only.</p><a href="#fnref:1" rev="footnote">↩</a></li>
<li id="fn:2">
In “Elements of Programming”
the term “limit” is used instead of “last” to avoid this confusion.
It also happens to start with the same letter, so
the abbrevation <code>[f, l)</code> can be read as either word.<a href="#fnref:2" rev="footnote">↩</a></li>
<li id="fn:3">
“No man ever steps in the same river twice.” - Heraclitus<a href="#fnref:3" rev="footnote">↩</a></li>
<li id="fn:4">
“Through the wire” refers to receiving data from a communication
device, such as the internet.
You read packets as they arrive, and they aren’t stored anywhere,
so once you read them, they are gone.<a href="#fnref:4" rev="footnote">↩</a></li>
<li id="fn:5">
<p>Another example of the <code>InputIterator</code> concept is <a href="https://en.wikipedia.org/wiki/Pipeline_(Unix)">UNIX pipes</a>.
Pipes transfer data which is output from one program, to the input of another.
Consider the following shell command:</p>
<pre><code>head -c 50000 /dev/urandom | gzip
</code></pre>
<p><code>head</code> reads 50000 random characters,
and immediately outputs it (to <code>stdout</code>).
This output then becomes the input for <code>gzip</code> (<code>stdin</code>)
which compresses it.</p>
<p>The two programs run concurrently not sequentially.
When <code>head</code> reads a small chunk of data, it can be immediately
written to <code>gzip</code>.
In this way, the data transfer operates like <code>InputIterator</code>.
Neither program has access to all the data at once.
They can only read pieces of data as they come in.
They can’t seek back earlier in the input.
Once it is read, it is gone.</p>
<p>The ability of <code>gzip</code> to operate on “input iterator”-like
streams is one of the reasons why it is so versatile.
It can compress data while it is being generated, or downloaded,
without being able to see the complete data.</p><a href="#fnref:5" rev="footnote">↩</a></li>
<li id="fn:6">
First find the min (<code>n - 1</code> comparisons), then find the max (<code>n - 1</code> comparisons).
<code>(n - 1) + (n - 1) = 2n - 2</code>.<a href="#fnref:6" rev="footnote">↩</a></li>
<li id="fn:7">
For more about this algorithm, see Alex’s presentation <a href="http://stepanovpapers.com/IraPohlFest.pdf">“One algorithm from The Book: A tribute to Ira Pohl”</a>.<a href="#fnref:7" rev="footnote">↩</a></li>
</ol>
</div>
<span style="float: right">
[
<a href="06_min_max.html">previous</a>,
<a href="index.html">contents</a>,
<a href="08_lisp.html">next</a>
]
</span>
</body>
</html>