-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path15_merge_inplace.html
428 lines (366 loc) · 15.3 KB
/
15_merge_inplace.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>15. Merge inplace</title>
<link rel="stylesheet" href="template/style.css">
</head>
<body>
<span style="float: right">
[
<a href="14_binary_search.html">previous</a>,
<a href="index.html">contents</a>,
<a href="16_optimizing_stable_sort.html">next</a>
]
</span>
<a name="L15.-Merge-inplace"></a>
<h1>15. Merge inplace</h1>
<a name="Reinventing-things"></a>
<h2>Reinventing things</h2>
<p>Another sad story (like the fish story)
is finding the algorithm for merging sorted lists.
This is a notoriously hard problem.
Many people worked on it.
The first solution was done by a Russian computer scientist
<a href="https://en.wikipedia.org/wiki/Alexander_Kronrod">Alexander Kronrod</a>,
but it wasn’t stable.
There was another solution by a wonderful Argentinian computer scientist <a href="https://www.genealogy.math.ndsu.nodak.edu/id.php?id=47194">Luis Pardo</a> (Knuth’s student).</p>
<p>So, I was thinking and thinking and thinking and once I was waking up in the phase between Twilight,
when you wake up but still see dreams but you’re not quite asleep.
I saw the algorithm on the board, it does happen.
I was ecstatic.
I think it was 1984.
What do you do if you find a really beautiful algorithm?
If you’re me, you call your friends.
So I called <a href="https://en.wikipedia.org/wiki/David_Musser">Dave Musser</a> and said, “this is absolutely gorgeous” and he agreed.
I started implementing and doing measurements.
Meanwhile, he starts telling faculty around him.</p>
<p>Here comes the bad news.
One of his colleagues, <a href="https://kaltofen.math.ncsu.edu/">Erich Kaltofen</a> who is a distinguished specialist in computer algebra, came to Dave and said
“Yeah it’s nice, but there are these two Polish guys Dudzinski and Dydek who published it in 1981<sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup> (two years before).”
It was very sad.
But, we often reinvent things.
Meanwhile Knuth heard about it from his friend <a href="https://en.wikipedia.org/wiki/Vaughan_Pratt">Vaughan Pratt</a> who told him about it.
So he gives the attribution to his friend, and not the two polish guys<sup id="fnref:2"><a href="#fn:2" rel="footnote">2</a></sup>.</p>
<p>As an algorithm itself, it’s utterly useless.
But sometimes algorithms published by theoreticians can be used by us, after appropriate modification.</p>
<a name="Merging-adjacent-lists"></a>
<h2>Merging adjacent lists</h2>
<p>We got into all of this because we were thinking about merge.
We already learned to merge linked list (chapter 12).
I introduced this thing called <code>goto</code>.
Today I’m going to teach you some other bad programming practices because it’s always
pleasant to introduce techniques which are known to be bad in general when
they’re good in particular.</p>
<p>We’re going to go about things in a funny way.
Normally when I teach merge,
we then realize it can be used for sorting.
We write merge sort and then we realize that merge sort needs extra memory,
and say “oh it’s very unfortunate. Couldn’t we find merge sort
that doesn’t require extra memory?”
This time around, I decided to follow a different path.
At first, we are going to avoid normal merge.
We’re going to start with very beautiful, but somewhat slow code.
Sometimes it’s actually good to start with slow code and refine it
into fast code.
Especially if it allows you to create something architecturally nice
and see connections.
So we are going to look at the much harder problem of in-place merge.
The problem is actually hard if you think about it.</p>
<a name="Interface"></a>
<h3>Interface</h3>
<p>What is the interface?
It’s not trivial.
Obviously if you have two separate lists/vectors,
you can’t really merge in place.
So the interface assumes they are adjacent.
One thing you could do is just sort it.
There are problems.
Most sorts, besides merge sort,
are not stable, so stability will be lost.</p>
<p>For bounded (not counted) it will take three iterators:</p>
<pre><code>first, middle, last
</code></pre>
<p>But our algorithm will greatly benefit from counted ranges.
When do we need counted ranges? When we do bisection,
or something like binary search.
We will use two of them:</p>
<pre><code>[first1, count1)
[first2, count2)
</code></pre>
<p>We have a precondition that <code>distance(first1, first2) == count1</code>.
Another precondition is that each range is sorted,
and our post condition is the entire range will be sorted.</p>
<a name="Algorithm"></a>
<h3>Algorithm</h3>
<p>If you don’t know how to do something, the old
advice is to look for divide and conquer.
The following is a graph of the two sorted ranges adjacent to each other.
The graph for each moves up and to the right to illustrate they are ascending.
When we have lots of variables naming doesn’t work.
We have to use one letter names with indices, like math.</p>
<pre><code> n0 n1
/ /
/ /
/ /
/ /
f0 f1
</code></pre>
<p>We will first bisect one of the ranges and pick a guy from the middle.
Then we ask, “where would it fit in the other sequence?”
Do we have a function for that?
We do. It’s called <code>lower_bound</code>.</p>
<p>Assume we bisect the left.
Then let <code>f0_0 = f0</code> and <code>f0_1</code> be the bisection of the first interval.
Then <code>f1_1</code> is found from the right using <code>lower_bound</code>.
(that should take <code>O(log(n))</code> comparisons).</p>
<pre><code> n0 n1
/ /
/ /
f0_1 f1_1
/ /
/ /
f0_0 f1
</code></pre>
<p>Now we are going to rotate.
Rotating swaps elements in the range
<code>[f0_1, f1_1)</code>
in such a way that <code>f1</code> becomes the first.
<code>[f0_0, f0_1)</code> and <code>[f1_1, n1)</code> remain fixed (see <a href="https://en.cppreference.com/w/cpp/algorithm/rotate"><code>std::rotate</code></a>).</p>
<pre><code> n0 n1
/ /
/ /
f0_1 f1_1
/ /
/ /
f0_0 f1
</code></pre>
<p>Now we know <code>f0_1</code> is in his rightful place (all lower are to the left and all greater are to the right),
so we will let <code>x = f0_1</code>,
as he won’t be moved again
So, we shrink the range by one step by assigning <code>f1_0 = f0_1 + 1</code>,
and then just figure out the lengths of the remaining
intervals:</p>
<pre><code> n1_0 n1_1
/ /
f1_0 /
x f1_1
n0_0 n0_1
/ /
/ /
f0_0 f0_1
</code></pre>
<p>Now notice that we have 4 adjacent sequences,
each of which is individually sorted, so we
can apply the algorithm recursively.</p>
<p>Here is the other insight.
Which range should we bisect?
The smaller one, because
we want to get to empty range as fast as possible.
So if it’s on the left we should use <code>lower_bound</code>
If it’s on the right we should use <code>upper_bound</code>.
Why?
To preserve stability we need to make sure equal
guys don’t jump over each other.</p>
<a name="Implementation"></a>
<h3>Implementation</h3>
<p>If you write a function like this it has to return
a lot of stuff.
Here comes the solution which we are proud of,
which is returning things through the reference arguments.
Here we take 2 ranges,
and return 4 of them.</p>
<pre><code>template <typename I, typename N, typename R>
// I is ForwardIterator
// N is Integral
// R is WeakStrictOrdering on the value type of I
inline
void merge_inplace_left_subproblem(I f0, N n0,
I f1, N n1,
I& f0_0, N& n0_0,
I& f0_1, N& n0_1,
I& f1_0, N& n1_0,
I& f1_1, N& n1_1,
R r) {
// precondition std::distance(f0, f1) == n0
// precondition is_sorted_n(f0, n0, r) && is_sorted(f1, n1, r)
// precondition n0 > 0
// precondition n1 > 0
f0_0 = f0;
n0_0 = n0 >> 1;
f0_1 = f0;
std::advance(f0_1, n0_0);
f1_1 = lower_bound_n(f1, n1, *f0_1, r);
f1_0 = std::rotate(f0_1, f1, f1_1);
n0_1 = std::distance(f0_1, f1_0);
++f1_0;
n1_0 = (n0 - n0_0) - 1;
n1_1 = n1 - n0_1;
}
</code></pre>
<p>Note that this <code>std::rotate</code> is the C++11 version which returns an iterator
rather than <code>void</code><sup id="fnref:3"><a href="#fn:3" rel="footnote">3</a></sup>.</p>
<p>Now implement the right sub-problem,
it is basically the same idea.
The fundamental difference is upper bound,
and switching sides.</p>
<pre><code>template <typename I, typename N, typename R>
// I is ForwardIterator
// N is Integral
// R is WeakStrictOrdering on the value type of I
inline
void merge_inplace_right_subproblem(I f0, N n0,
I f1, N n1,
I& f0_0, N& n0_0,
I& f0_1, N& n0_1,
I& f1_0, N& n1_0,
I& f1_1, N& n1_1,
R r) {
// precondition std::distance(f0, f1) == n0
// precondition is_sorted_n(f0, n0, r) && is_sorted(f1, n1, r)
// precondition n0 > 0
// precondition n1 > 0
f0_0 = f0;
n0_1 = n1 >> 1;
f1_1 = f1;
std::advance(f1_1, n0_1);
f0_1 = upper_bound_n(f0, n0, *f1_1, r);
++f1_1;
f1_0 = std::rotate(f0_1, f1, f1_1);
n0_0 = std::distance(f0_0, f0_1);
n1_0 = n0 - n0_0;
n1_1 = (n1 - n0_1) - 1;
}
</code></pre>
<p>Now we combine them in a function that does no work.</p>
<pre><code>template <typename I, typename N, typename R>
// I is ForwardIterator
// N is Integral
// R is WeakStrictOrdering on the value type of I
void merge_inplace_n(I f0, N n0,
I f1, N n1, R r) {
// precondition std::distance(f0, f1) == n0
// precondition is_sorted_n(f0, n0, r) && is_sorted(f1, n1, r)
if (!n0 || !n1) return;
I f0_0, f0_1, f1_0, f1_1;
N n0_0, n0_1, n1_0, n1_1;
if (n0 < n1) merge_inplace_left_subproblem(f0, n0,
f1, n1,
f0_0, n0_0,
f0_1, n0_1,
f1_0, n1_0,
f1_1, n1_1,
r);
else merge_inplace_right_subproblem(f0, n0,
f1, n1,
f0_0, n0_0,
f0_1, n0_1,
f1_0, n1_0,
f1_1, n1_1,
r);
merge_inplace_n(f0_0, n0_0, f0_1, n0_1, r);
merge_inplace_n(f1_0, n1_0, f1_1, n1_1, r);
}
</code></pre>
<a name="Naming-things"></a>
<h3>Naming things</h3>
<p>There is a function in STL incorrectly called <a href="https://en.cppreference.com/w/cpp/algorithm/inplace_merge"><code>std::inplace_merge</code></a>
Why is the name incorrect?
Paul discovered it while working
on the index to our book (Elements of Programming) and discovered
a general principle which escaped me for decades.
“inplace merge”
is a bad name for a function?
Why it should be <code>merge_inplace</code>.
It should come next to merge in the index.
People who look into the index want to see all the versions.
Am I a total idiot?
I guess, I did not see it.</p>
<p>I’m just emphasizing a very important naming principle
which is to think about indexing.
think about indexing things you know like
<code>find_if</code>, not <code>if_find</code>.
Suffixes should be sorted in the order of importance.</p>
<a name="Sort-from-merge"></a>
<h2>Sort from merge</h2>
<p>Now we can sort, using our merge mechanism.
It’s really easy.
The first statement is that an empty list is sorted.
The second is that a one element list is sorted.
Now, we just call it recursively and ask
it to sort itself.
Nobody does any work except <code>merge_inplace_n</code><sup id="fnref:4"><a href="#fn:4" rel="footnote">4</a></sup>.</p>
<pre><code>template <typename I, typename N, typename R>
// I is ForwardIterator
// N is Integral
// R is WeakStrictOrdering on the value type of I
I sort_inplace_n(I first, N n, R r) {
if (!n) return first;
N half = n >> 1;
if (!half) return ++first;
I middle = sort_inplace_n(first, half, r);
I last = sort_inplace_n(middle, n - half, r);
merge_inplace_n(first, half, middle, n - half, r);
return last;
}
</code></pre>
<p>It’s a good algorithm.
It’s stable.
It uses no extra storage.
Whether that’s really needed or not, we don’t know.
It has <code>log(n)</code> levels.
At every level we have a merge which is <code>O(n log(n))</code>.
so the overall complexity is <code>O(n log^2(n))</code>.
It’s better than bubble sort and shell sort.</p>
<p>There is another strength of this algorithm,
which you won’t know unless you think about generic programming.
What’s the requirement on the iterator?
Just forward iterator.
We can sort anything.</p>
<p>But, it also sucks.
Where does it suck? Deep down in the call tree.
At the top it’s good.
But, we are doing too much work.
We will talk more about this in the next
lesson.</p>
<p><strong>Exercise:</strong> The requirement to use no extra storage is a little unrealistic.
Try to write a version that is similar, but utilizes extra storage.</p>
<a name="Code"></a>
<h2>Code</h2>
<ul>
<li><a href="code/merge_inplace.h">merge_inplace.h</a></li>
<li><a href="code/test_merge_inplace.cpp">test_merge_inplace.cpp</a></li>
</ul>
<div class="footnotes">
<hr/>
<ol>
<li id="fn:1">
<a href="papers/on-stable-merge.pdf">“On a Stable Minimum Storage Merging Algorithm”</a>. Information Processing Letters. 1981.<a href="#fnref:1" rev="footnote">↩</a></li>
<li id="fn:2">
See exercise 5.5.3 (Pg. 390) in Volume 3 of “The Art of Computer Programming”.
The algorithm itself and the attribution to Vaughan Pratt is in the solution (Pg. 701).<a href="#fnref:2" rev="footnote">↩</a></li>
<li id="fn:3">
Alex: When I first put <code>std::rotate</code> in STL it returned <code>void</code>.
In 1995 I discovered what it should return and how to do it efficiently.
When you rotate you return what the new middle is.
It took literally 20 years.<a href="#fnref:3" rev="footnote">↩</a></li>
<li id="fn:4">
<p>If you are not familiar with recursion or mathematical induction
this kind of code can look tricky.
The key property is that every iteration the problem space is made smaller,
in a way that it preserves essential properties of the original problem.</p>
<p>In this case, we assume we can sort both halves. That wouldn’t solve the
problem normally, except that the merge algorithm gives us a way to combine them
to get a solution for the full input space.</p><a href="#fnref:4" rev="footnote">↩</a></li>
</ol>
</div>
<span style="float: right">
[
<a href="14_binary_search.html">previous</a>,
<a href="index.html">contents</a>,
<a href="16_optimizing_stable_sort.html">next</a>
]
</span>
</body>
</html>