tag:blogger.com,1999:blog-11349538349550720382017-05-12T14:17:28.400-07:00Sorting and searchingTomek Czajkanoreply@blogger.comBlogger3125tag:blogger.com,1999:blog-1134953834955072038.post-77465620386404858192015-09-26T01:24:00.000-07:002015-09-26T02:15:09.087-07:00Radix sort: sorting integers (often) faster than std::sort.This post will describe a very simple integer sorting algorithm: radix sort. Despite its simplicity, it is a very practical algorithm. As we will see, even a simple implementation can easily outperform std::sort from the C++ standard library.<br /><br />Suppose we start with an array of numbers such as this:<br /><pre>853, 872, 265, 238, 199, 772, 584, 204, 480, 173,</pre><pre>499, 349, 308, 314, 317, 186, 825, 398, 899, 161<br /></pre>Counter-intuively, we begin by sorting it based on the <b>least</b> significant decimal digit: <br /><pre>480, 161, 872, 772, 853, 173, 584, 204, 314, 265,</pre><pre>825, 186, 317, 238, 308, 398, 199, 499, 349, 899<br /></pre>Now, we sort it based on the middle decimal digit. But we take care that we do this in a <b>stable </b>fashion, that is: for numbers that are tied on the middle digit, keep them in the current order. <br /><pre>204, 308, 314, 317, 825, 238, 349, 853, 161, 265,</pre><pre>872, 772, 173, 480, 584, 186, 398, 199, 499, 899<br /></pre>The numbers are now sorted by the last two digits. It is not hard to guess what we will do next. Once we have sorted them by the most significant digit, taking care not to change the order in case of ties, we will have sorted the array.<br /><br />I haven't said <b>how</b> exactly we perform the sorting based on a single digit, so let's do this last round slowly. We use count-sort. Here is how it works:<br /><b><br /></b><b>Step 1</b>. Go through the data and count how many times each top digit appears. 0 appears 0 times, 1 appears 4 times, etc.:<br /><pre></pre><pre>count: 0, 4, 3, 5, 2, 1, 0, 1, 4, 0<br /></pre><b><br /></b><b>Step 2</b>. Compute the prefix sums in count. This will give us, for each digit, the index of the first entry with that digit in the final sorted order. <br /><pre></pre><pre>position: 0, 0, 4, 7, 12, 14, 15, 15, 16, 20<br /></pre>For instance, we now know that numbers starting with the digit 4 will begin at index 12.<br /><b><br /></b><b>Step 3</b>. Shuffle the data. For each number, we simply place it directly at the correct position! After placing a number we increment the index for the given digit.<br /><pre>X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X</pre><pre>position: 0, 0, 4, 7, 12, 14, 15, 15, 16, 20</pre><pre>X, X, X, X, 204, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X</pre><pre>position: 0, 0, 5, 7, 12, 14, 15, 15, 16, 20<br /></pre><pre>X, X, X, X, 204, X, X, 308, X, X, X, X, X, X, X, X, X, X, X, X<br /></pre><pre>position: 0, 0, 5, 8, 12, 14, 15, 15, 16, 20<br /></pre><pre>X, X, X, X, 204, X, X, 308, 314, X, X, X, X, X, X, X, X, X, X, X<br /></pre><pre>position: 0, 0, 5, 9, 12, 14, 15, 15, 16, 20<br /></pre><pre>...<br /></pre><pre>161, 173, 186, 199, 204, 238, 265, 308, 314, 317,</pre><pre>349, 398, 480, 499, 584, 772, 825, 853, 872, 899<br /></pre><b><br /></b><b>Step 4</b>. We have shuffled the data into a new, temporary array. Move it back to the original array. In practice, we can simply swap pointers here. <br /><br /><h3>Running time</h3><br />Of course in practice we don't sort based on decimal digits. We could sort based on individual bits but we can do better than that. Sort based on <b>groups</b> of bits.<br /><br />If we sort k bits at a time, there are 2<sup>k</sup> possible "digits". The count array will need to be of that length. Hence, let's make k ≤ log<sub>2</sub> n, so that the helper array isn't longer than the data being sorted.<br /><br />For added performance, it may be useful to make k somewhat smaller than log<sub>2</sub> n. In our implementation below, we use k = ⌊log<sub>2</sub> n / 3⌋. This increases the number of rounds 3-fold, but has several advantages that outweigh that: <br /><ul><li>The count array only uses n<sup>1/3</sup> memory.</li><li>Computing the prefix sums in step 2 takes negligible time.</li><li>Counting in step 1 doesn't randomly increment counters all over memory. It randomly increments counters in a tiny section of memory, which is good for cache performance.</li><li>Shuffling in step 3 doesn't randomly write all over memory. It writes consecutively in only n<sup>1/3</sup> different locations at a time, which also improves cache performance.</li></ul>For the purposes of analyzing asymptotic performance, we simply say: k = Θ(log n). If the numbers being sorted have ω bits, we have Θ(ω / log n) rounds, each round is done in Θ(n) time, hence the total running time of radix sort is:<br /><br /><span style="font-size: large; font-weight: normal;">Θ(n ω / log n)</span><br /><br />Note what this means. The larger the n, the <b>less</b> time we spend per element! This is in contrast with comparison-based sorts, where we spend Θ(log n) per element, which increases with n.<br /><br />This indicates that there is a threshold: for small n it is better to use a comparison-based sort. For large n, radix sort is better.<br /><br />What is the threshold? It should be about when ω / log n ≈ log n, that is, when n ≈ 2<sup>√ω</sup>. For instance, when ω=64, n ≈ 2<sup>8</sup> = 256 or so should be the threshold. If n is significantly bigger than this, radix sort should start to dominate. <br /><br /><h3>C++ implementation</h3><pre>template<class T><br />void radix_sort(vector<T> &data) {<br /> static_assert(numeric_limits<T>::is_integer &&<br /> !numeric_limits<T>::is_signed,<br /> "radix_sort only supports unsigned integer types");<br /> constexpr int word_bits = numeric_limits<T>::digits;<br /><br /> // max_bits = floor(log n / 3)<br /> // num_groups = ceil(word_bits / max_bits)<br /> int max_bits = 1;<br /> while ((size_t(1) << (3 * (max_bits+1))) <= data.size()) {<br /> ++max_bits;<br /> }<br /> const int num_groups = (word_bits + max_bits - 1) / max_bits;<br /><br /> // Temporary arrays.<br /> vector<size_t> count;<br /> vector<T> new_data(data.size());<br /><br /> // Iterate over bit groups, starting from the least significant.<br /> for (int group = 0; group < num_groups; ++group) {<br /> // The current bit range.<br /> const int start = group * word_bits / num_groups;<br /> const int end = (group+1) * word_bits / num_groups;<br /> const T mask = (size_t(1) << (end - start)) - T(1);<br /><br /> // Count the values in the current bit range.<br /> count.assign(size_t(1) << (end - start), 0);<br /> for (const T &x : data) ++count[(x >> start) & mask];<br /><br /> // Compute prefix sums in count.<br /> size_t sum = 0;<br /> for (size_t &c : count) {<br /> size_t new_sum = sum + c;<br /> c = sum;<br /> sum = new_sum;<br /> }<br /><br /> // Shuffle data elements.<br /> for (const T &x : data) {<br /> size_t &pos = count[(x >> start) & mask];<br /> new_data[pos++] = x;<br /> }<br /><br /> // Move the data to the original array.<br /> data.swap(new_data);<br /> }<br />}<br /><br /></pre><h3>Experiments</h3><br />I have generated arrays of random 64-bit integers and timed the time per element it takes to sort using std::sort and radix_sort. <br /><br /><table border="1" cellpadding="2" cellspacing="0"><tbody><tr><th>n</th><th>std::sort</th><th>radix_sort</th></tr><tr><td><div style="text-align: right;">10</div></td><td><div style="text-align: right;">3.3 ns</div></td><td><div style="text-align: right;">284.2 ns</div></td></tr><tr><td><div style="text-align: right;">100</div></td><td><div style="text-align: right;">6.1 ns</div></td><td><div style="text-align: right;">91.6 ns</div></td></tr><tr><td><div style="text-align: right;">1 000</div></td><td><div style="text-align: right;">19.3 ns</div></td><td><div style="text-align: right;">59.8 ns</div></td></tr><tr><td><div style="text-align: right;">10 000</div></td><td><div style="text-align: right;">54.8 ns</div></td><td><div style="text-align: right;">46.8 ns</div></td></tr><tr><td><div style="text-align: right;">100 000</div></td><td><div style="text-align: right;">66.9 ns</div></td><td><div style="text-align: right;">40.1 ns</div></td></tr><tr><td><div style="text-align: right;">1 000 000</div></td><td><div style="text-align: right;">81.1 ns</div></td><td><div style="text-align: right;">40.8 ns</div></td></tr><tr><td><div style="text-align: right;">10 000 000</div></td><td><div style="text-align: right;">95.1 ns</div></td><td><div style="text-align: right;">40.7 ns</div></td></tr><tr><td><div style="text-align: right;">100 000 000</div></td><td><div style="text-align: right;">108.4 ns</div></td><td><div style="text-align: right;">40.6 ns</div></td></tr></tbody></table><br />We see the effect as predicted: for std::sort, the running time per element increases with n, for radix_sort it decreases with n. It's not exactly proportional and inversely proportional to log n due to various effects (mostly cache sizes), but the trend is there. Most importantly: for large n, radix_sort is clearly winning!<br /><br /><h3>Further optimizations</h3><br />More optimizations are possible which can lead to improvements in performance. In particular:<br /><ul><li>Optimize the number of rounds as a function of n. Taking log n / 3 bits at a time is a rough guess at what should work well.</li><li>Currently we scan the data array twice in each iteration: once to count, a second time to shuffle. It can be reduced to a single scan: while shuffling based on the current digit, we could also be counting the next digit at the same time.</li></ul><div>These tweaks might improve the algorithm by a constant factor. Next time, I will describe how to get a better <b>asymptotic</b> running time. Until then!</div><br /><ul></ul>Tomek Czajkahttps://plus.google.com/113633403228999637061noreply@blogger.com1tag:blogger.com,1999:blog-1134953834955072038.post-38397216656140804482015-05-17T02:45:00.000-07:002015-05-17T14:24:53.968-07:00How fast can we sort?We all know that we can sort n things in O(n log n) time and that is the best you can do. Problem solved. Right? <b>Wrong!</b><br /><br />Sorting is a fascinating topic and I am planning a whole series of posts about it. It also inspired the blog name.<br /><br />Let's start with what most programmers already know.<br /><br /><h3>Classic sorting algorithms</h3><div><br />O(n log n) sorting algorithms have been known for a very long time. John von Neumann already implemented merge sort in 1945 on the EDVAC computer. We're talking about a computer built out of vacuum tubes, with 1000 words of RAM, capable of performing 1000 operations per second or so.<br /><br />Later people discovered quicksort in 1962<sup>[1]</sup> and heapsort in 1964<sup>[2]</sup>. The only theoretical improvement here is that heapsort is in-place: it uses only O(1) additional memory outside the array. Of course the heap-based priority queue is nice in its own right.<br /><br />We can easily implement another O(n log n) sorting algorithm, AVL-sort, using the code from my <a href="http://sorting-and-searching.blogspot.com/2015/04/balanced-binary-search-trees-easy-way.html">previous post</a> on balanced binary search trees. We just put all the elements into an AVL tree, and the extract them back into a list:<br /><pre>avlSort :: Ord t => [t] -> [t]<br />avlSort = toList . fromList<br /></pre><h3></h3><h3>Lower bound for comparison-based sorting</h3><br />Suppose that we restrict ourselves to performing only one operation on the elements we're sorting: compare two of them to see which one is bigger. This is what we mean by "comparison-based sorting".<br /><br />Every comparison operation returns a single yes or no answer. If we perform k such operations, we can get 2<sup>k</sup> different sequences of answers, and hence we can distinguish between 2<sup>k</sup> different permutations. Since there are n! permutations of n elements, it follows that we need at least log<sub>2</sub> (n!) comparisons in the worst case (and also on average, which is slightly harder to see) to distinguish between them all.<br /><br />log<sub>2</sub> (n!) ≥ log<sub>2</sub> (n/2)<sup>(n/2)</sup> = n/2 * (log<sub>2</sub> n - 1) = Θ(n log n) <br /><br />So there you go. That's the proof of the lower bound.<br /><br /><b>The significance of this lower bound has been overblown.</b> Why would you ever so restrict yourself as to only use comparisons?? You can do much more with numbers, or other objects that you'd want to sort, than just compare two of them. You can add them, you can multiply them, you can index arrays with them... All these other operations don't seem all that useful for sorting at first sight. But it turns out they are useful! This is very unintuitive, and fascinating at the same time.<br /><br />Again and again I have seen people cite this result when it does not apply. Most commonly, the claim is that n <b>numbers</b> can't be sorted faster than O(n log n). For example, people will claim that it's impossible to compute convex hulls in 2D faster than O(n log n), because that requires sorting coordinates. As we will see in a moment, this claim is false. Numbers <b>can</b> actually be sorted faster than this!<br /><br /><ul></ul><h3></h3><h3></h3><h3></h3><h3>Faster sorting algorithms</h3><br />Let's start talking about some asymptotically faster sorting algorithms. What are some of the things we normally want to sort?<br /><br />The first group is numbers: integers, rational numbers, floating-point real numbers, complex numbers... OK maybe not complex numbers, they don't have any natural ordering.<br /><br />The second group is sequences of characters or numbers, such as text strings (e.g. names) or big multi-precision integers.<br /><br /><h3>Sorting integers</h3><br />Important note here: we are talking about sorting integers that fit in a single machine word, such as 64-bit integers on a 64-bit computer. In general, we will be talking about sorting w-bit integers on a w-bit computer. This is not an artificial restriction: comparison-based sorting algorithms need this as well. Well, we can allow a constant multiple, such as 2w-bit integers on a w-bit computer. After all, we can implement operations on 2-word integers in O(1) time. But we're not talking about huge, multiple-precision integers. If you want to sort million-bit integers, you have to either find a 1000000-bit computer, or skip to the section about sorting sequences.<br /><br />Here is a summary of various algorithms for sorting integers. I will be writing about some of them in my future posts.<br /><br /><table border="1" cellspacing="0"><tbody><tr><td>long ago</td><td>merge sort</td><td>O(n log n)</td></tr><tr><td>long ago</td><td>radix sort</td><td>O(n w / log n)</td></tr><tr><td>1977</td><td>van Emde Boas <sup>[3]</sup></td><td>O(n log w)</td></tr><tr><td>1983</td><td>Kirkpatrick & Reisch <sup>[4]</sup></td><td>O(n log (w / log n))</td></tr><tr><td>1995</td><td>Andersson, Hagerup, Nilsson, Raman <sup>[6]</sup></td><td>O(n log log n)</td></tr><tr><td>2002</td><td>Han & Thorup <sup>[7]</sup></td><td>O(n (log log n)<sup>1/2</sup>)</td></tr></tbody></table><br />Some of these run-times depend on w, but the last two are clearly better than O(n log n), independently of w. <br /><br /><h3>Is sorting integers in O(n) time possible?</h3><br />This is the big open problem. Nobody knows.<br /><br />Radix sort does it when n is big compared to the word size (log n = Ω(w)).<br /><br />In their 1995 paper <sup>[6]</sup>, Andersson et al showed how to do this when n is small compared to the word size (log n = O(w<sup>1/2-ɛ</sup>) for some ɛ>0). There is still a gap in between where we just don't know.<br /><br />Update: It has been pointed out in the comments that this knowledge gap has been slightly tightened on the "small n compared to the word size" side. As of 2014<sup>[8]</sup>, we know how to sort in O(n) time when log n = O((w / log w)<sup>1/2</sup>).<br /><br /><h3></h3><h3></h3><h3></h3><h3>What about other kinds of numbers?</h3><br />Real numbers are typically represented in a floating point format. This seems harder to handle than integers, but it's really not. Floating point numbers are represented as two integers: an exponent and a mantissa. For instance, the IEEE double-precision floating point format, the most common representation out there, stores real numbers as an 11-bit exponent and a 52-bit mantissa. The representation is: 2<sup>exponent</sup> * (1 + mantissa * 2<sup>-52</sup>). A number with a higher exponent is bigger than a number with a smaller exponent. For equal exponents, the number with the bigger mantissa is bigger. So really, sorting these real numbers is equivalent to sorting 63-bit integers!<br /><br />Sorting rational numbers can also be reduced to sorting integers. If you have rational numbers a/b, where a and b are w-bit integers, compute ⌊a * 2<sup>2w</sup> / b⌋ for each, and sort the resulting 3w-bit integers. This works because a difference between two different rationals a/b and c/d is always at least 1/(bd) > 2<sup>-2w</sup>, so a precision of 2w bits after the binary point is sufficient.<br /><br />This is another reason sorting integers is an interesting topic: if we can sort integers, we can sort all kinds of numbers.<br /><br /><h3>Sorting strings lexicographically</h3><br />The important thing to notice here is that we can't compare two elements in constant time any more in this case. Therefore, merge-sort does not work in O(n log n) time. It can be shown that it works in O(L log n) time, where L is the sum of lengths of the strings.<br /><br />This too can be improved. In 1994, Andersson and Nillson <sup>[5]</sup> showed how to sort strings in O(L + (time to sort n characters)) time. If the alphabet is small (such as ASCII), we can use count sort to sort the n characters, which gives time complexity O(L + |Σ|), where |Σ| is the size of the alphabet. If the alphabet is large, we can use one of the integer sorting algorithms and arrive at, say, O(L + n (log log n)<sup>1/2</sup>) time.<br /><br />This also works for sorting multi-precision integers. If you append their lengths at the start, this is just lexicographic sorting, where the "characters" are word-size numbers. <br /><br /><h3>References</h3><br />[1] Hoare, Charles AR. "Quicksort." The Computer Journal 5.1 (1962): 10-16.<br />[2] Williams, John William Joseph. "ALGORITHM-232-HEAPSORT." Communications of the ACM 7.6 (1964): 347-348. <br />[3] van Emde Boas, Peter. "Preserving order in a forest in less than logarithmic time and linear space." Information processing letters 6.3 (1977): 80-82. <br />[4] Kirkpatrick, David, and Stefan Reisch. "Upper bounds for sorting integers on random access machines." Theoretical Computer Science 28.3 (1983): 263-276. <br />[5] Andersson, Arne, and Stefan Nilsson. "A new efficient radix sort." Foundations of Computer Science, 1994 Proceedings., 35th Annual Symposium on. IEEE, 1994.<br />[6] Andersson, Arne, et al. "Sorting in linear time?." Proceedings of the twenty-seventh annual ACM symposium on Theory of computing. ACM, 1995. <br />[7] Han, Yijie, and Mikkel Thorup. "Integer sorting in O (n√(log log n)) expected time and linear space." Foundations of Computer Science, 2002. Proceedings. The 43rd Annual IEEE Symposium on. IEEE, 2002. <br />[8] Belazzougui, Djamal, Gerth Stølting Brodal, and Jesper Sindahl Nielsen. "Expected Linear Time Sorting for Word Size Ω(log<sup>2</sup> n log log n)." Algorithm Theory–SWAT 2014. Springer International Publishing, 2014. 26-37. </div>Tomek Czajkahttps://plus.google.com/113633403228999637061noreply@blogger.com2tag:blogger.com,1999:blog-1134953834955072038.post-79267384267443204782015-04-21T00:00:00.000-07:002015-05-17T16:23:53.119-07:00Balanced binary search trees: the easy wayThe task of balancing binary search trees has a reputation of being very hard to implement. Data structure books seem to list dozens of different cases, especially for deleting elements.<br /><br />Let's change this - it's not that hard! The analysis will be a little involved, but the code is going to be simple.<br /><br />Here are some design choices:<br /><ul><li>We'll implement AVL trees. I initially started writing this in terms of 2-3 trees. Then I decided AVL was going to be even simpler.</li><li>All elements are stored in the leaves. This is unusual, people usually store values in internal nodes. But it makes things so much simpler!</li><li>Internal nodes store a reference to the smallest (left-most) element of the sub-tree. This will be useful to guide us down the tree.</li><li>Internal nodes also store the sub-tree height. AVL trees are usually described with nodes only storing the height difference of their children, but storing the height instead makes things easier still.</li><li>We'll implement this in Haskell. We like algebraic data types for trees!</li></ul><table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody><tr><td style="text-align: center;"><a href="http://4.bp.blogspot.com/-OnUm463JbSg/VTdE9L-CxdI/AAAAAAAABCY/hcbriioyWFE/s1600/avl.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" src="http://4.bp.blogspot.com/-OnUm463JbSg/VTdE9L-CxdI/AAAAAAAABCY/hcbriioyWFE/s1600/avl.png" /></a></td></tr><tr><td class="tr-caption" style="text-align: center;">Example AVL tree.</td></tr></tbody></table><br /><br /><br />OK, let's get down to it!<br /><br /><h3>Preliminaries</h3><div><br /></div><div>Start by defining binary trees.</div><pre>data Tree t = Empty | Leaf t | Node Int t (Tree t) (Tree t)<br /></pre>A tree of elements of type t is either empty, it is a leaf, or it is an internal node. A leaf contains a value of type t. An internal node contains: the height, the smallest element in the sub-tree, and the two children. Write some helper functions: <br /><pre>height :: Tree t -> Int<br />height Empty = error "height Empty"<br />height (Leaf _) = 0<br />height (Node h _ _ _) = h<br /><br />smallest :: Tree t -> t<br />smallest Empty = error "smallest Empty"<br />smallest (Leaf x) = x<br />smallest (Node _ s _ _) = s<br /><br />left, right :: Tree t -> Tree t<br />left (Node _ _ a _) = a<br />left _ = error "only internal nodes have children"<br />right (Node _ _ _ b) = b<br />right _ = error "only internal nodes have children"<br /><br />toList :: Tree t -> [t]<br />toList Empty = []<br />toList (Leaf x) = [x]<br />toList (Node _ _ a b) = toList a ++ toList b<br /></pre><br />The toList function is not optimal: it works in Θ(n log n) time (why?). Θ(n) is possible. I'll leave that as a coding exercise.<br /><br />Time for some AVL-specific stuff. How do we build and balance trees? As a reminder, this is how AVL trees work:<br /><ul><li>All elements in the left sub-tree should be smaller (or equal) to all the elements in the right sub-tree.</li><li>The difference in height of the two sub-trees should be at most 1. We call this "similar height".</li></ul>Create another little helper function: build a tree from two sub-trees of similar height:<br /><pre>node :: Tree t -> Tree t -> Tree t<br />node a b<br /> | abs (height a - height b) <= 1<br /> = Node (max (height a) (height b) + 1) (smallest a) a b<br /> | otherwise = error "unbalanced tree"</pre>It's finally time to start manipulating our trees:<br /><br /><h3>Merging trees</h3><br />Wait, what? Merging trees as the first operation? What about insert?<br /><br />We'll get to insert later. As you'll see, merge is going to be our basic operation. Everything else will be defined in terms of it!<br /><br />What do we mean by merge? Suppose we have two trees, A and B, such that all elements of A are smaller or equal to all elements of B. The merged tree will contain all elements from both.<br /><br />The "node" operation works when the two trees have similar heights. What if their heights differ by more than 1? Assume that A is the shorter tree. Some helpful notation that we will use:<br /><ul><li>A + B means A merged with B</li><li>A.L, A.R are the left and right sub-trees</li><li>A[h] is a tree of height h</li><li>A[h<sub>1</sub>..h<sub>2</sub>] is a tree whose height is between h<sub>1</sub> and h<sub>2</sub> (inclusive)</li><li>{A,B} is a tree whose children are A and B. A = {A.L, A.R}</li></ul>So, again: we're trying to merge a tree A[0 .. h-2] with another tree B[h]. Our strategy is going to be as follows: merge A with B.L, then merge the resulting tree with B.R. Does this work?<br /><br /><table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody><tr><td style="text-align: center;"><a href="http://2.bp.blogspot.com/-HzWnXf2FI08/VTdFSUiy3FI/AAAAAAAABCg/jFTsD-x9h9U/s1600/avl1.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="149" src="http://2.bp.blogspot.com/-HzWnXf2FI08/VTdFSUiy3FI/AAAAAAAABCg/jFTsD-x9h9U/s1600/avl1.png" width="640" /></a></td></tr><tr><td class="tr-caption" style="text-align: center;">Recursively merging a small tree with a larger tree.</td></tr></tbody></table><br /><br />A[0 .. h-2] + B[h] = (A[0 .. h-2] + B.L[h-2 .. h-1]) + B.R[h-2 .. h-1] = [h-2 .. h] + B.R[h-2 .. h-1]<br /><br />How do we know that the tree resulting from the first merge has height in the range [h-2 .. h]? It's because merging two trees of heights h<sub>1</sub> and h<sub>2</sub> will always result in a tree of height either max(h<sub>1</sub>, h<sub>2</sub>) or max(h<sub>1</sub>, h<sub>2</sub>) + 1. This is certainly true for similar-height trees. Go ahead and verify that it will remain true in other cases as well.<br /><br />OK, so what exactly happened when we tried to merge two trees with non-similar heights? After the recursive merge, we reduced the height difference to at most 2. Now what? Let's see if the same process works for a height difference of exactly 2:<br /><br />A[h-2] + B[h] = (A[h-2] + B.L[h-2 .. h-1]) + B.R[h-2 .. h-1]<br /> = {A[h-2], B.L[h-2 .. h-1]} + B.R[h-2 .. h-1] = [h-1 .. h] + B.R[h-2 .. h-1]<br /><br />The trees A and B.L now have similar heights, so their merge is easy. If B.R has height h-1, the final merge is also easy.<br /><br />What if it has height h-2? Then B[h] = {B.L[h-1], B.R[h-2]} and:<br /><br /><table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody><tr><td style="text-align: center;"><a href="http://4.bp.blogspot.com/-Eu3UNPZJgFo/VTdF-mdO7LI/AAAAAAAABCw/r433mC9Gu40/s1600/avl2.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="158" src="http://4.bp.blogspot.com/-Eu3UNPZJgFo/VTdF-mdO7LI/AAAAAAAABCw/r433mC9Gu40/s1600/avl2.png" width="640" /></a></td></tr><tr><td class="tr-caption" style="text-align: center;">Special case: bad!</td></tr></tbody></table><br /><br />A[h-2] + {B.L[h-1], B.R[h-2]} = (A[h-2] + B.L[h-1]) + B.R[h-2] = {[h-2], [h-1]} + [h-2]<br /><br /><b>Uh oh!</b> Can you see what happened?<br /><br />We tried to merge [h-2] with {[h-1], [h-2]}, and reduced the problem to merging {[h-2], [h-1]} with [h-2]. That's the mirror image of the original problem! No improvement. If we keep doing this, we'll get into an infinite loop!<br /><br />We need to use a different strategy in this special case, to break the cycle. Fortunately, it's easy: A, B.L.L, B.L.R, B.R all have similar heights! Just pair them up.<br /><br /><table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody><tr><td style="text-align: center;"><a href="http://3.bp.blogspot.com/-gCdtTnenxVY/VTdGNbJMgWI/AAAAAAAABC4/ATkDnYmSblg/s1600/avl3.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="129" src="http://3.bp.blogspot.com/-gCdtTnenxVY/VTdGNbJMgWI/AAAAAAAABC4/ATkDnYmSblg/s1600/avl3.png" width="640" /></a></td></tr><tr><td class="tr-caption" style="text-align: center;">Special case: good.</td></tr></tbody></table><br /><br />A[h-2] + {B.L[h-1], B.R[h-2]} = A[h-2] + B.L.L[h-3 .. h-2] + B.L.R[h-3 .. h-2] + B.R[h-2] = {{A, B.L.L}, {B.L.R, B.R}}<br /><br />Here is the code:<br /><pre>merge :: Tree t -> Tree t -> Tree t<br />merge Empty x = x<br />merge x Empty = x<br />merge a b<br /> | abs (height a - height b) <= 1<br /> = node a b<br /> | height a == height b - 2 && height (right b) == height b - 2<br /> -- the special case: [h-2] + {[h-1],[h-2]}<br /> = let (bl,br) = (left b, right b)<br /> (bll,blr) = (left bl, right bl)<br /> in node (node a bll) (node blr br)<br /> | height a < height b<br /> = merge (merge a (left b)) (right b)<br /> | otherwise<br /> = merge (left a) (merge (right a) b)<br /></pre>That's it! Pretty short, huh? That's all we need.<br /><br />How long does a merge take? We always reduce the difference in heights in the first recursive call, and finish by merging two trees of heights differing by at most 2, which takes constant time. Therefore, merging two trees of heights h<sub>1</sub> and h<sub>2</sub> takes O(|h<sub>1</sub> - h<sub>2</sub>| + 1) time.<br /><br /><h3>Splitting trees</h3><br />Now we want to do the reverse of merging: split a tree into two smaller trees. OK but split where? We need some way of telling which elements belong to the left part and which elements belong to the right part.<br /><br />This is accomplished by a functional argument: a function that returns "false" for the left elements and "true" for the right elements. The requirement is that the function is monotonic: we can't have x < y and x belonging to the right while y belongs to the left. Other than that, any function will do. Often, this will be something like: put x <= 5 on the left and x > 5 on the right.<br /><br />Is splitting going to be more complicated than merging? No! It's going to be simpler. In fact, we will use merging to do splitting!<br /><br />Here is where having the reference to the smallest element of a sub-tree comes in handy:<br /><ul><li>If the smallest element of the right sub-tree belongs to the left, the whole left sub-tree belongs to the left, and we only need to split the right sub-tree.</li><li>If the smallest element of the right sub-tree belongs to the right, the whole right sub-tree belongs to the right, and we only need to split the left sub-tree.</li></ul><br /><pre>split :: Tree t -> (t->Bool) -> (Tree t, Tree t)<br />split Empty _ = (Empty, Empty)<br />split (Leaf x) isBig<br /> | isBig x = (Empty, Leaf x)<br /> | otherwise = (Leaf x, Empty)<br /><br />split (Node _ _ a b) isBig<br /> | isBig (smallest b)<br /> = let (a1,a2) = split a isBig<br /> in (a1, merge a2 b)<br /> | otherwise<br /> = let (b1,b2) = split b isBig<br /> in (merge a b1, b2)<br /></pre><br />Done.<br /><br />How fast is it? Since each merge can take Θ(log n) time, are we running the risk of having split run in Θ(log<sup>2</sup> n) time?<br /><br />Fortunately, not.<br /><br />Let T(h, h<sub>1</sub>, h<sub>2</sub>) be the maximum run-time of split of a tree of height h that will return two trees of heights h<sub>1</sub>, h<sub>2</sub>.<br /><br />Suppose that we are in the first case of the code above: we are splitting the left sub-tree a, and then merging a2 with b. If the height of a2 is h<sub>3</sub>, then the run-time for the recursive split and the following merge is:<br />T(h-1 [or h-2], h<sub>1</sub>, h<sub>3</sub>) + O(h<sub>2</sub> - h<sub>3</sub> + 1)<br />Similarly in the second case.<br /><br />Notice how the merge time is "paid for" by a corresponding decrease in one of the h's. In other words, when we have to do a long merge because of a small tree returned from a recursive call, it means we had less work to do in that recursive call.<br /><br />By induction: T(h, h<sub>1</sub>, h<sub>2</sub>) = O(h + h<sub>1</sub> + h<sub>2</sub>) = O(log n).<br /><br /><h3>Insert, delete, etc</h3>Now that we have split and merge, we can do anything we want, easily!<br /><br /><pre>contains :: Ord t => Tree t -> t -> Bool<br />contains a x =<br /> case split a (>=x) of<br /> (_, Empty) -> False<br /> (_, b) -> smallest b == x<br /><br />insert :: Ord t => Tree t -> t -> Tree t<br />insert a x =<br /> let (a1, a2) = split a (>=x)<br /> in merge a1 (merge (Leaf x) a2)<br /><br />delete :: Ord t => Tree t -> t -> Tree t<br />delete a x =<br /> let (b, _) = split a (>=x)<br /> (_, c) = split a (>x)<br /> in merge b c<br /><br />fromList :: Ord t => [t] -> Tree t<br />fromList = foldl insert Empty<br /></pre><br /><h3>Let's see if it works</h3><br /><pre>$ ghci Tree.hs<br />GHCi, version 7.4.1: http://www.haskell.org/ghc/ :? for help<br />Loading package ghc-prim ... linking ... done.<br />Loading package integer-gmp ... linking ... done.<br />Loading package base ... linking ... done.<br />[1 of 1] Compiling Tree ( Tree.hs, interpreted )<br />Ok, modules loaded: Tree.<br />*Tree> let a = fromList [10, 5, 7, 18, 3]<br />*Tree> toList a<br />[3,5,7,10,18]<br />*Tree> toList (insert a 4)<br />[3,4,5,7,10,18]<br />*Tree> toList (delete a 10)<br />[3,5,7,18]<br />*Tree> contains a 12<br />False<br />*Tree> contains a 5<br />True<br />*Tree> let (b,c) = split a (\x -> x*x > 50)<br />*Tree> toList b<br />[3,5,7]<br />*Tree> toList c<br />[10,18]<br /></pre><br /><b>Yay!</b>Tomek Czajkahttps://plus.google.com/113633403228999637061noreply@blogger.com1