<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hesham Elkhatib on Medium]]></title>
        <description><![CDATA[Stories by Hesham Elkhatib on Medium]]></description>
        <link>https://medium.com/@hesham.elkhatib92?source=rss-6465b2677f5d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ySZYhhPN299kuBZ8u4kUDg.jpeg</url>
            <title>Stories by Hesham Elkhatib on Medium</title>
            <link>https://medium.com/@hesham.elkhatib92?source=rss-6465b2677f5d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:28:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hesham.elkhatib92/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding B-Trees]]></title>
            <link>https://medium.com/@hesham.elkhatib92/understanding-b-trees-552cf2b1ca7e?source=rss-6465b2677f5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/552cf2b1ca7e</guid>
            <category><![CDATA[filesystem]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Hesham Elkhatib]]></dc:creator>
            <pubDate>Mon, 07 Jan 2019 23:59:06 GMT</pubDate>
            <atom:updated>2019-01-12T23:52:21.561Z</atom:updated>
            <content:encoded><![CDATA[<h3>Emergence of B-Trees</h3><p>On the early days on working with files, files were so small that sequential access was sufficient for data retrieval, but as files grew in size there was a need to add indexes to files.</p><p>Indexes made retrieval faster by eliminating the need to do a sequential search to finally reach the target, a list of keys and pointers is stored in a smaller file that could be searched more quickly, with the key and pointer the large, primary file can be accessed.</p><p>Unfortunately, simple indexes had sequential flavor as the primary data files and as the primary data grew, indexes grew too in a way that made managing them so inefficient specially with dynamically changing data (that is mutable).</p><p>In 1963, the idea of applying balanced binary search trees has emerged, but it turned out they aren’t so efficient to work on disks (we will see why later).</p><p>In 1972, B-trees has been announced to the world with an article titled “ Organization and Maintenance of Large Ordered Indexes” as the solution to access and efficiently maintain an index that is too large to hold in memory.</p><p>Today, B-Trees are considered the most widely used data structures for indexing in database management systems (DBMS).</p><p>The goal of this article is not only to understand how B-Trees work, but also to have a good idea of why they are designed the way they are and how they are different from other in-memory binary search trees despite trying to solve a very similar problem (i.e. provide an efficient way to query a dynamic data).</p><h3>Hard Disks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-3CuyH0a8L5_LWGJgK7Pw.jpeg" /><figcaption>Hard disk access requires mechanical movements</figcaption></figure><p>Before diving deep into B-Trees internals we need to remember two facts about hard disks.</p><ol><li><strong>Disk accesses are extremely slow!</strong></li></ol><p>As opposed to RAM, accessing data from a hard disk requires mechanical movements, these make it much much slower than main memory, how much slower? the time it takes to get information from RAM is about 100 nanoseconds. Getting the same information from disks might take 30 milliseconds that is a quarter of a million times longer than the memory access!</p><p>Hence, the main driving factor of designing algorithms that uses hard disks is reducing the number of read/write operations. Designing B-Tress was no exception.</p><p><strong>2. Access operations are done in pages</strong></p><p>In order to amortize the time spent waiting for mechanical movements, disk access doesn’t get one item at a time, but information is divided into equal sized pages of bytes and disk access is done to an entire one or more pages.</p><p>The page size depends on the manufacturer but it’s typically ²¹¹ to ²¹⁴ bytes.</p><p>As we will see later, this behavior has a great impact on how a B-Tree node is designed.</p><p>Now that we have reviewed these two important factors about hard disks, we are ready to discuss the nitty gritty details, let’s gooo!</p><h3>B-Trees performance</h3><p>B-Tree was the result of the efforts to discover a general method for storing and retrieving data in large file systems with low cost. It meets that goal being a self-balancing search tree that does searching, deletion and insertion efficiently in O(log n) (where <strong>n</strong> is the number of records) which is determined by the height of the tree (exactly like in-memory binary search trees).</p><p>Also, it maintains the natural order of the stored keys, so that they can be retrieved in linear time.</p><h3>B-Trees Characteristics</h3><p>Each B-Tree operation leaves the B-Tree holding a set of characteristics so that a height of log(n) is guaranteed. Let’s discuss those characteristics.</p><h4>A generalization of binary trees</h4><p>B-Trees are a generalization of binary trees, each node stores <strong>m</strong> keys in sorted order and has <strong>(m+1)</strong> children. Each key then covers a range of values underneath it.</p><p>Let’s suppose a node contains keys k1 ≤ k2 ≤ k3 ≤ …. km. Then it will have t0, t1, t2, t3 ….. tm sub-trees respectively where:</p><ul><li>t0 keys are less than k1.</li><li>tm keys are greater than km</li><li>ti (where i &gt; 0 and i &lt; m) keys are between ki and k(i+1)</li></ul><p><strong>So, how much is “m”?</strong></p><p>Before answering that, wait for a second! why there is an “m” in the first place? Why make life more complicated and have a larger branching factor (.i.e the number of children per node) than 2? isn’t binary trees much simpler?</p><p>As mentioned earlier the driving factor of designing programs that do disk operations is to reduce the number of disk accesses as much as we can, a node should store as many data as possible so that we get the most out of that expensive disk access operation. So, a B-tree node is allowed to store as much as a whole disk page can hold. Consequently, the number <strong>m </strong>depends on the underlying page size.</p><p>Also, having a larger branching factor means having a smaller height, having a smaller height means having a smaller number of those expensive disk accesses.</p><p>And that’s exactly why having a larger branching factor in B-Trees is much more important than having it with in-memory data structures.</p><p>To have a practical idea of how large branching factors dramatically improves performance with B-Trees, imagine a tree that has over one billion keys, and a branching factor of 1001 (a common branching factor for B-trees is between 50 and 2000) would result in a height of 2 meaning that searching for any key in that tree would require only two disk accesses!</p><h4>Minimum and Maximum degrees</h4><p>Each node has a minimum and a maximum number of children it could have.</p><p>Let’s define these bounds in terms of a constant <strong>t</strong> (<strong>t</strong> ≥ 2), <strong>t</strong> being the minimum and <strong>2t</strong> being the maximum. This t is chosen such that a node storing <strong>2t — 1</strong> keys and <strong>2t</strong> pointers would fit in a whole disk page.</p><p>This rule has an <strong>exception</strong> for the root, the root node can have at least 2 children, regardless of the value of <strong>t</strong>.</p><h4>All the leaf nodes have the same depth which is the tree’s height</h4><p>This property is maintained by having the tree grow from the bottom up as opposed to the popular in-memory search trees.</p><p>But how maintaining those characteristics guarantees height <strong>h</strong> that is less than or equal to <strong>log(n)?</strong> let’s prove that right now!</p><p>Since the root will have at least 2 children and each node on the subsequent levels will have at least <strong>t</strong> children, then the first level will have 1 node (the root of course!), the 2nd level will have at least two nodes, the 3rd level will have at least <strong>2t</strong> nodes, the 3rd one will have at least <strong>2t² </strong>the 4th one will have <strong>2t⁴ </strong>…. etc.</p><p>That the number of keys <strong>n</strong>, satisfies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*puLKDK_sKBWmChXZ0SnsKg.png" /></figure><p>Evaluating the sum of the geometric sequence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*CBvvG6yo92snZd_LFv4Zsg.png" /></figure><p>Hence</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*O-M6utoplaMUce9q_Yr8zw.png" /></figure><p>By doing simple algebra and taking the base-t logarithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*oJ469dOJJCLZmLTU-05eXg.png" /></figure><p>Which proves that a B-tree following the above characteristics will have a height that is proportional to log(n).</p><p>Now that we have discussed the characteristics, let’s dive deep into the Action!</p><h4>The Query Operation</h4><p>The query operation of the B-Tree is the simplest one compared to the insert and the delete operations. It’s a direct generalization of the query operation for binary search trees.</p><p>We traverse from top to bottom starting from the root and if the target key isn’t one of the keys of the current node we go down one level by choosing one of the current node’s children based on comparisons with the current nodes’ keys.</p><p>With binary search trees, it was simpler since there was only one key, we go left or right depending on whether the target key is less than or greater than the key of the current node, respectively.</p><p>Here, we have m sorted keys each represent a dividing point of ranges of the keys below that node, what we will do is to search for the first key (starting from the smallest one) that is strictly greater than the target key, and will follow the child descending from that key, that’s it we do that until we find our target key.</p><h4>The insert Operation</h4><p>The insert operation is a little bit more complicated. The most important thing about it is that it leaves the tree balanced after being performed.</p><p>Let’s see how can we do it!</p><p>As opposed to binary search trees, B-trees grow from bottom to top, so the first thing an insert operation does is searching for the leaf node that covers the target key and <strong>tries </strong>to store the new key in it, if it can’t insert it in the leaf node, it won’t create a child for that leaf node, instead a far more interesting thing happens!</p><p>As you might have noticed we said it “<strong>tries</strong>” to insert the key in the leaf node, so what <strong>tries </strong>here means?</p><p>As you might remember a property of a B-tree is that it maintains a maximum number of keys <strong>m</strong> each node can store, so if the leaf node already contains <strong>m</strong> keys, we can’t insert the new key in it.</p><p>Instead, an interesting thing happens, what is called a <strong>split</strong> operation is performed on that leaf node.</p><p><strong>Spiting a node</strong></p><p>The splitting operation is done by:</p><ol><li>Moving the median of the keys to the node’s parent.</li><li>Split the leaf node into two separate nodes, the set of keys before the median and the set of keys after the median.</li><li>Make the pointer on the left side of the median (which has just been moved to the parent), points to the node with the smaller keys.</li><li>Make the pointer on the right side of the median (which has just been moved to the parent), points to the node with the bigger keys.</li></ol><p>If the splitting is done to the root node, a new parent node will be created before moving the median to it, and that new parent will become the tree new root. Remember? that’s why the root has the exception of having only 2 children.</p><p>But wait for a second! in the first step of the splitting operation, we move the median to the parent node, what if that parent node already is full?</p><p>Do the splitting operation on the parent then? and what if the parent of the parent need to be split? do that to the grandfather? and go all the way up right?</p><p>This means that we might need two passes, one all the way down and one all the way up, in order to avoid that and do it with a single pass like what we do with binary search trees, we don’t wait to reach the bottom in order to find out whether we will actually need to do a split, Instead as we go down searching for the leaf node the new key belongs, we do the split operation for all the full nodes on our way, that way we are assured that the parent node won’t be full and whenever we need to split a full node (including the leaf of course).</p><p>The delete operation is more complicated compared to the insert operation, we won’t discuss it in that article, but you got the point right?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=552cf2b1ca7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>