<?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 David Urbina on Medium]]></title>
        <description><![CDATA[Stories by David Urbina on Medium]]></description>
        <link>https://medium.com/@WindUpDurb?source=rss-2cf21ec322b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yGNIfCpne4m6iZxwyGeBWg.jpeg</url>
            <title>Stories by David Urbina on Medium</title>
            <link>https://medium.com/@WindUpDurb?source=rss-2cf21ec322b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 20:46:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@WindUpDurb/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[Weeds: A Story and Thoughts on Life]]></title>
            <link>https://medium.com/swlh/weeds-a-story-and-thoughts-on-life-a2d38ecaa0f2?source=rss-2cf21ec322b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2d38ecaa0f2</guid>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[fiction]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[short-story]]></category>
            <dc:creator><![CDATA[David Urbina]]></dc:creator>
            <pubDate>Mon, 16 Sep 2019 04:38:26 GMT</pubDate>
            <atom:updated>2019-10-01T02:12:06.981Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TRl_ZgbEUgNDnJgOEXjDpw.png" /><figcaption>Illustration was created by Lucy González</figcaption></figure><p><em>For Anna Banana, my fierce fighter of a sister</em></p><p>Tito didn’t believe in ghosts, but after the last three nights, he began to have doubts. He was normally a heavy sleeper and over the years he had grown accustomed to the train that ran past his shack of a house. As the train blitzed on by every few hours, he’d just snooze on through it. But the past three nights something strange out there had been waking him up.</p><p>As he came out of his slumber that first night, he realized someone was out there walking around near the tracks. Each step on the track ballast was soft, but in the night’s silence, they crunched as the foot made contact with the crushed stone. Then came the humming, hollow but serene in its melody.</p><p>The past three nights he tossed and turned in bed, tracking the path of what was out there. Each night at midnight, the faint footfalls sounded in the distance. With each passing minute, the steps grew just a bit louder until ten past midnight when the humming began.</p><p>That first night he was convinced a homeless woman was out there until he heard the steps on the track ballast that covered his backyard. The song and steps seemed to go through the enclosing chain-linked fence, making its way three times around his house before leaving him sleepless until dawn.</p><p>This night, it was a minute before midnight and he couldn’t afford another night without sleep, so when it hit midnight and he heard the approaching footsteps, he sat up in bed and waited. At eight past midnight, he got up, crouched his way to the window that looked into the backyard, and peeked his head out, waiting for whatever it was to begin its first lap. When he heard the steps over the stones in his backyard, he moved, swung the door open, and jumped outside.</p><p>“Hey,” said Tito. “¡Oye! I can’t sleep with all this racket and I have work to find tomorrow morning.” He didn’t end there and went on, pouring out all of his worries. “My bills are stacking up. My rent is late. And if I don’t get sleep — because of you — well, then I won’t find work and I’ll be homeless. And if I’m homeless,” he trailed off, catching his breath. Tito realized no one was out there and wondered if he was losing his mind, but before too long, he heard her.</p><p>“¿Y qué? Why does it matter if you’re homeless?”</p><p>The response didn’t startle him. Her voice lulled his frustrations so that when he turned to face her, an abuela, he spoke at ease and with weary honesty.</p><p>“Then, I’ll be on the streets. And I won’t be happy.”</p><p>“Are you happy now?” she asked, stepping towards him. Her silver hair was as bright as moonlight.</p><p>“No, but that’s not the point,” he shot back. “I just know that if I don’t pay the rent this time, I’ll be kicked out and I will have nothing. And how will I be happy if I have nothing?”</p><p>“Follow me,” she said.</p><p>Tito winced with each barefooted step on the stones and the spiky weeds that grew through them. She took him further into his backyard, which wasn’t large by any standard, but just enough for one person. For the years he had been living there, he hardly spent any time in his backyard. Walking in it, now, under the moonlight, following a silver-haired abuela in a white dress embroidered with flowers in earthy yellows, aquas, teals, and chili pepper reds, his backyard felt unfamiliar, but still, vaguely like home.</p><p>“If you can be rid of all of the weeds here,” she said, “I will give you everything you need to be happy.”</p><p>He knew there was no reason to question her. Something in his gut, something in the depths of his being told him that if he did what she said, it would come true, that it must come true, and he was determined to find out.</p><p>The abuela no longer visited him after that night, but he did not forget about what she had said. He spent his mornings searching for work to little success. With a belly half full of lunch, he would then work on his backyard in the afternoons and early evenings.</p><p>The first day he pulled out the weeds by hand. In his anger at the day’s failure in finding work, he feverishly yanked each one that crossed his path. As he ripped out the weeds, they sliced his palms, which only stoked him further. By the end of the day, his hands ached and were covered in cuts.</p><p>The second day Tito wore gloves. At the end of the day, he stood smirking at the weed-less land. But that night, the abuela didn’t come.</p><p>On the third day, he awoke to find new weeds had sprouted through the stones. He realized, then, that pulling them wasn’t going to work, as they’d only grow back.</p><p>The following days he tried everything he could think of to kill the weeds. He showered herbicide, but that only caused the next generation of weeds to grow back thicker and thornier. He soaked his backyard with gasoline and lit the drenched weeds ablaze, but eventually more sprouted through the charred stones. He removed all of the track ballast in his backyard, dug into the earth and shuffled the soil around, tearing at the roots, but even then, the weeds came back anew. Days and countless failed attempts had gone by, but every other morning, the weeds would be poking out of the earth.</p><p>One morning, after Tito had exhausted all ideas, he sighed and shook his head in defeat. That night in bed, as he stared at the ceiling, he heard her in the distance. He rose in excitement, but his body sagged as he remembered his failures. He slouched his way to his backyard and sat cross-legged on the earth. Weeds cut at his bare legs, but he didn’t care then. He just sat in silence, listening to the abuela ’s melody as it grew louder.</p><p>“¿Y qué?” she finally asked.</p><p>“I failed,” Tito sighed. “I couldn’t do it.”</p><p>“What did you try?”</p><p>He listed each attempt, but nothing, he said, worked. They always came back. “They always came back,” he repeated, softer. “Always. Maybe I’m not meant to be happy.”</p><p>Remember this, she said that night. We cannot pull out our weeds. We cannot burn or poison them. Maybe they will be gone for a time, but we cannot expect to be forever rid of our weeds through these destructive actions. We can, though, care for our land. We can plant seeds, water them, and over time, stalks will rise out of the earth and bloom into a bounty of flowers. We can plant seeds and grow beautiful flowers to cover our earth — and that will drive out the weeds.</p><p>Like Tito, we all have our weeds. Our metaphorical weeds, though, exist in our mind. These are the weeds of doubt, anger, anxiety, jealousy, and hatred, among other negative emotions. Sometimes we don’t even realize they are there, but they are, marring the soil of our mind, unbeknown to us, but influencing our thoughts, words, actions, and behaviors.</p><p>Sometimes all it takes is time spent in self-reflection to realize that there in the backyard of our minds the soil has been corrupted by weeds. What, then, can we do if we strive to be the best version of ourselves? What, then, can we do as we strive for meaning in life?</p><p>We grow flowers in the soil of our mind — by having good thoughts, by speaking good words, and by doing good deeds. These are the seeds that, if we nurture through consistency, grow into flowers. These are the seeds that, if grown into flowers, help to create an internal world teeming with beauty, one where our self-growth can flourish.</p><p>But while having good thoughts, speaking good words, and doing good deeds sound simple enough, practicing them can be a bit more of a challenge, especially when negative thoughts seem to sprout out of nowhere and without our control. That’s normal. That’s human. And that should always be expected. While we may never be able to control everything out there in the world — nor the world of our mind — we will always have the fundamental freedom to control our response.</p><p>A judgemental thought may spawn out of the blue, or we may spurt out something mean, or we may unintentionally hurt someone. Shit happens and we’re only human. But when these reactions, which are influenced by the weeds of our mind, rise to the surface, we should respond to them with love and compassion. Ignoring these negative reactions is like being blind to the weeds in our backyard. Shaming, blaming, or attacking ourself are ineffective attempts at killing the weeds. But responding to these reactions with understanding and an intention to learn and grow will yield a field flowing with flowers.</p><p>I have found that maintaining positivity in my thoughts, words, and actions through difficult and frustrating times doesn’t always beget positive results in the world. But continuing to plant those seeds and continuing to care for them has its own reward. This reward exists in you and it can’t be taken away; this reward is knowing that, in spite of everything, you tried to be the best person you can be and you contributed something positive to this world, even if it’s something as tiny as a “Good afternoon. How are you doing?” That’s what matters at the end of the day. Failures and successes come and go, but how we feel about ourselves, and our words and actions — that stays with us. If we are happy with who we are, then what else do we need? If we are unhappy with who we are, then there’s nothing out there in the world that could change that.</p><p>There are many reasons to practice good thoughts, good words, and good deeds, but let’s conclude reflecting on this: doesn’t enjoying a beer with family and friends in a backyard covered in flowers sound much more appealing than chilling in an unkempt, weed-infested backyard? Yeah, I’ll take the flowers. And the beer, please.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2d38ecaa0f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/weeds-a-story-and-thoughts-on-life-a2d38ecaa0f2">Weeds: A Story and Thoughts on Life</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Heapsort]]></title>
            <link>https://medium.com/@WindUpDurb/on-heapsort-3678b00e31b2?source=rss-2cf21ec322b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3678b00e31b2</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[David Urbina]]></dc:creator>
            <pubDate>Mon, 09 Oct 2017 00:00:00 GMT</pubDate>
            <atom:updated>2019-08-28T03:37:20.170Z</atom:updated>
            <content:encoded><![CDATA[<p>Heapsort is one of my favorite sorting algorithms because it highlights the importance of considering the right data structures in algorithm design. Heapsort also has an upper-bound <em>O(n log n)</em> time complexity, which isn’t bad, since comparison-based sorting algorithms have a lower bound of <em>Ω(n log n)</em>.</p><p>This post will explore the foundations of the heapsort — selection sort and the heap — before providing an overview of heapsort. Lastly, we will review both in-place and out-of-place implementations of heapsort in C# and Javascript.</p><h3>Selection Sort</h3><p><strong>Selection sort</strong> is an in-place, comparison-based sorting algorithm that builds the sorted array through incremental insertions, or swaps.</p><p>The in-place property of the algorithm is derived from dividing the targeted array into unsorted and sorted portions.</p><p>The algorithm works by linearly scanning the unsorted portion of the array for the largest item, subsequently swapping it with the last item in the unsorted section. This is followed by moving the partition, which reduces the range of the unsorted portion and increases the length of the sorted items.</p><p>This results in a worst-case and average-case quadratic time complexity, making it impractical on large arrays.</p><p>The <em>O(n2)</em> time complexity is caused by the consecutive linear scans for the largest item in the array. This is a direct effect of the data structure used in the algorithm: an array.</p><p>But there are other data structures that we can use to efficiently identify the largest item in a set, namely a binary heap.</p><h3>Binary Heap</h3><p>A <strong>binary heap</strong> is a binary tree-based data structure that satisfies the heap property. In addition, since a binary heap is a type of heap, it is also an implementation of a priority queue.</p><p>First, the <strong>heap property</strong> states that for any node within the tree, it must dominate both of its children. In the case of a <strong>max-heap</strong>, any given node must have a greater value than both of its children. In the case of a <strong>min-heap</strong>, any given node must have a smaller value than both of its children.</p><p>As an implementation of a priority queue, an abstract data type, a binary heap supports the basic operations of Add, or Insert, in logarithmic time; FindMin, or FindMax, in constant time; and DeleteMin, or DeleteMax, in logarithmic time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nxgLuZTgBPr14NxR.png" /></figure><h3>Array-Implemented Binary Heap</h3><p>Binary heaps are most commonly implemented with an array as the underlying data structure, providing a space-efficient way to represent a binary tree without the space taken up by pointers.</p><p>Nodes within the binary tree are indexed in the array using the following equations:</p><p>The equation to find the index of a node in a 1-based indexed array: <br> 2l — 1through 2l- 1 Where l is the level in the tree, and the root level is at l = 1</p><p>The equation to find the index of a node in a 0-based indexed array: <br> 2l — 1- 1 through 2l- 2 Where l is the level in the tree, and the root level is at l = 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gRyTroeG3OcPdRMB.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RTsNVhnagXn1jLtf.png" /></figure><p>In addition, the index of the left and right child of a node, along with its parent, can be found using the following equations:</p><p>Formulas to find children and parent in 1-based indexed array: k = the index of a node left child = 2k right child = 2k + 1 parent = k / 2</p><p>Formulas to find children and parent in 0-based indexed array: k = the index of a node left child = 2k + 1 right child = 2k + 2 parent = (k — 1) / 2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kqni-4Y-8trqY4D5.png" /></figure><h3>Limitations of a Binary Heap</h3><p>The benefits gained from an array representation of a binary tree are in exchange for some limitations. It should be emphasized that an array implementation of a binary heap can only efficiently represent a binary tree, and not a binary search tree. The loss of pointers in an array implementation of a binary heap results in a loss of flexibility that affects its ability to efficiently reorganize subtrees.</p><p>Whereas in a binary search tree subtrees could be swiftly reorganized by pointing the root elsewhere, in an array this would require repositioning every individual element involved in the restructuring of the tree, making the ordeal cumbersome. And if we recall, an important condition to maintain the logarithmic look-up time in a binary search tree is its balance — and that requires performing rotations, which involves restructuring subtrees.</p><p>This leads us to the next limitation of an array implementation of a heap: there is no efficient search operation. Because a binary heap does not represent a binary search tree, there is a loose partial order on the items that result in the search operation having at least a linear lower bound time complexity.</p><p>But there are benefits to the loose partial order, which are seen in the aforementioned three basic operations of a priority queue: insert; find-min, or find-max; and delete-min, or delete-max.</p><h3>Heapsort Is Selection Sort with a Heap</h3><p>Heapsort is basically the selection sort algorithm — an algorithm that builds a sorted array thorough incremental insertions — with the exception of using a heap. Recall that the unsorted array in selection sort requires a linear scan to find the largest item to insert next in the sorted portion, resulting in a quadratic time complexity for the algorithm. A binary heap, on the other hand, identifies the largest item in constant time, but the follow-up replacement with the next largest item is done in logarithmic time, resulting in a <em>O(n log n)</em> time complexity, which is ideal for a comparison-based sorting algorithm.</p><p>The only downside to heapsort, which in my opinion isn’t much of a downside, is that it requires more code to implement than a simple selection sort. This extra code is from having to build our own heap. So, let’s check out some code for a heap class that I built in both C# and Javascript.</p><h3>C# Code</h3><p>Here is the code for the <strong>Heap class</strong>:</p><pre>Please find my code at <a href="https://davidurbina.blog/on-heapsort/">https://davidurbina.blog/on-heapsort/</a></pre><p>Here is the code for the <strong>in-place and out-of-place heapsort methods</strong>:</p><pre>Please find my code at <a href="https://davidurbina.blog/on-heapsort/">https://davidurbina.blog/on-heapsort/</a></pre><p>And here is the code that <strong>tests</strong> both heapsort methods:</p><pre>Please find my code at <a href="https://davidurbina.blog/on-heapsort/">https://davidurbina.blog/on-heapsort/</a></pre><h3>Javascript Code</h3><p>Here is the code the for the <strong>Heap class</strong>:</p><pre>Please find my code at <a href="https://davidurbina.blog/on-heapsort/">https://davidurbina.blog/on-heapsort/</a></pre><p>Here is the code for <strong>in-place and out-of-place heapsort functions</strong>:</p><pre>Please find my code at <a href="https://davidurbina.blog/on-heapsort/">https://davidurbina.blog/on-heapsort/</a></pre><p>And here is the code that <strong>tests</strong> both heapsort functions:</p><pre>Please find my code at <a href="https://davidurbina.blog/on-heapsort/">https://davidurbina.blog/on-heapsort/</a></pre><h3>Thoughts on Code</h3><p>While both versions of heapsort run in <em>O(n log n)</em> time, the regular in-place version does require less space. In fact, it should have <em>O(1)</em> space complexity, whereas the out-of-place version that I created should have a <em>O(n2)</em> space complexity.</p><p>Despite the drastic difference in the space complexity between the two versions, I still like the out-of-place version for learning and understanding the algorithm, as the abstraction of the operations makes it easier to understand: first, a heap is created and then the extractMax method is continuously called on the heap until the sorted array is incrementally built up. For those approaching this algorithm for the first time, this version gives you that high-level illustration of the algorithm.</p><p>There’s also the benefit of the out-of-place version not mutating the original input, which could be of use in certain scenarios. But I’m certain revisions could be made to reduce the space complexity to <em>O(n)</em>.</p><p>Still, in practice, the in-place heap-sort is probably your best choice because of the <em>O(1)</em> space complexity.</p><h3>Conclusion</h3><p>Heapsort is a very practical sorting algorithm because it has an upper-bound time complexity of <em>O(n log n)</em>, which if we recall, is the lower-bound time complexity of any comparison-based sorting algorithm. This means that heapsort belongs to the set of functions that perform as quick as any comparison-based sorting algorithm can perform.</p><p>In addition, this distinction of being a <em>O(n log n)</em> comparison-based sorting algorithm is derived from the choice of data structure in the algorithm. The logic behind heapsort is very similar to the logic in selection sort. But the key difference behind the upper-bound superlinear time in heapsort and the upper-bound quadratic time in selection sort is the tactic used to identify the largest item in the unsorted portion — which is a direct result from the choice of the underlying data structure used in the algorithm: it takes a linear scan to find the largest item in an unsorted array, but it takes logarithmic time to bubble up the largest item in a heap.</p><p>Besides being a very practical sorting algorithm, I appreciate heapsort because it is a reminder of the importance of choosing the right data structures in algorithm design, as it can make the difference between <em>O(n2)</em> and <em>O(n log n)</em> performance.</p><p><em>Originally published at </em><a href="https://davidurbina.blog/on-heapsort/"><em>davidurbina.blog</em></a><em> on October 9, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3678b00e31b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Partial Ordering, Total Ordering, and The Topological Sort]]></title>
            <link>https://medium.com/@WindUpDurb/on-partial-ordering-total-ordering-and-the-topological-sort-9f9c0d0d812f?source=rss-2cf21ec322b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f9c0d0d812f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[David Urbina]]></dc:creator>
            <pubDate>Fri, 29 Sep 2017 00:00:00 GMT</pubDate>
            <atom:updated>2019-08-28T03:32:51.309Z</atom:updated>
            <content:encoded><![CDATA[<p>Scheduling problems — problems that seek to order a sequence of tasks while preserving an order of precedence — can be solved by performing a topological sort on a directed acyclic graph (DAG). Certainly, we can review the DAG and the topological sorting algorithms. But that does not go deep enough and it does not fully explore the mechanisms behind why a DAG paired with a topological sort is an effective solution. To more thoroughly understand the problem and the solution, a deeper dive has to be taken — and that means understanding the mathematics behind it.</p><p>Order theory is the branch of mathematics that we will explore as we probe partial ordering, total ordering, and what it means to the directed acyclic graph and topological sort.</p><p>We will begin with a partial order and a partially ordered set and examine how these concepts are related to a directed acyclic graph. This will be followed by an examination of a total order and a totally ordered set. With this foundation, we will be able to tackle the topological sort and its usefulness in scheduling problems.</p><h3>Partial Order</h3><p>A <strong>partial order</strong>, or <strong>partial ordering</strong>, is a relation between pairs of elements in a set. More specifically, it is a relation that is <strong>reflexive</strong>, <strong>transitive</strong>, and <strong>antisymmetric</strong>.</p><p>Given the set <em>S {1, 2, 3}</em>, the properties of reflexivity, transitivity, and antisymmetry can be explained using the ≤ relation as follows.</p><p>The <strong>reflexive</strong> property states that an element is equal, or comparable, to itself:</p><p>The <strong>transitive</strong> property states that there is an order of precedence in a chain of elements:</p><p>Transitive Property If 1 ≤ 2 And 2 ≤ 3 Then 1 ≤ 3</p><p>The <strong>antisymmetric</strong> property states that given a relation R, two elements cannot be related to each other if they are distinct elements. More formally, if aRb and a ≠ b, then bRa. But if aRb and a = b, then bRa.</p><p>Antisymmetric Property If 1 ≤ 2 Then 2 ≰ 1</p><p>Because the ≤ relation satisfies the reflexive, transitive, and antisymmetric properties, it is a partial order on the set <em>{1, 2, 3}</em>.</p><p>Another common example of a partial order is alphabetical order. Replace the set above with the set <em>{a, b, c}</em> and you’ll find that an alphabetical order satisfies the properties of reflexivity, transitivity, and antisymmetry.</p><h3>The Poset</h3><p>A <strong>partially ordered set</strong>, or <strong>poset</strong>, denoted as <em>(S, R)</em>, is a set S with a partial order R. Let’s take our aforementioned set S and partial order R and denote it as the partially ordered set <em>({1, 2, 3}, ≤)</em>.</p><p>The items in this set are ordered under the relation aRb where a ≤ b. An example of this set contains the following items:</p><p>{(1, 1), (1, 2), (1, 3), (2, 2) (2, 3), (3, 3)}</p><p>Each ordered pair above represents one of the elements in the poset <em>({1, 2, 3}, ≤)</em>.</p><p>For example, the ordered pair <em>(1, 1)</em> illustrates the reflexive property of a partial order because 1 ≤ 1.</p><p>The ordered pair <em>(1, 3)</em> represents the transitive property of a partial order because 1 ≤ 2 and 2 ≤ 3, so 1 ≤ 3.</p><p>And lastly, because <em>(2, 1)</em>, <em>(3, 1)</em>, and <em>(3, 2)</em> are not elements of the set, the antisymmetric property is satisfied.</p><h3>The Partial in Partial Order</h3><p>It is important to note that two elements <em>a</em> and <em>b</em> of a poset <em>(S, ≼)</em> are <strong>comparable</strong> if it is the case that <em>a ≼ b</em> or <em>b ≼ a</em>; otherwise, if neither is the case, <em>a</em> and <em>b</em> are <strong>incomparable</strong>. Here, the ≼ sign denotes a partial order.</p><p>In the poset <em>({1, 2, 3}, ≤)</em>, the partial order is the ≤ relation. Because for whatever <em>a</em> and <em>b</em> we choose from the elements <em>{1, 2, 3}</em>, it will be true that either <em>a ≤ b</em> or <em>b ≤ a</em>. For example, if <em>a = 1</em> and <em>b = 2</em>, it is true that a ≤ b. So, it can be said that these elements, 1 and 2, from the set are comparable.</p><p>But if the poset contained a random letter as well, such as in the poset <em>({1, 2, 3, z}, ≤)</em>, it would be the case that the element <em>z</em> is incomparable with the other elements. Elements <em>1, 2, 3</em> are comparable with each other, but when <em>a = z</em> or <em>b = z</em>, it is not true that <em>a &lt;= b</em> or <em>b &lt;= a</em>; therefore, <em>z</em> is an incomparable element in the poset because you cannot relate a letter to a number using the ≤ relation.</p><p>This is important to note because a partially ordered set is considered <strong><em>partially</em></strong> ordered; that is, every element within the set does not have to be comparable and there can exists incomparable elements within it.</p><p>When it is the case that every element is comparable, then the partially ordered set is considered a totally ordered set, and this will be discussed shortly.</p><h3>A DAG Is A Poset</h3><p>Before continuing to discuss total orderings, I would like to offer some relevance for why the partially ordered set is being discussed alongside directed acyclic graphs and topological sorting.</p><p>Straightforwardly, a directed acyclic graph is a partially ordered set, which I can illustrate through an example.</p><h4>An Example Through Dinner</h4><p>Let’s say that I have planned out a simple dinner with my girlfriend, and I have a number of tasks that I need to complete. But I realize that some tasks depend on other tasks, so I have to finish some tasks before others. This has the potential to be a bit overwhelming to plan, but we do have graph theory and order theory at hand to make it much more manageable.</p><p>I first decide to determine every task that I have to do and collect them into a set <em>T {A, B, C, D, E, F, G, H}</em>.</p><p>T = {A, B, C, D, E, F, G, H} where A = Buy Ingredients at Market B = Make Guacamole C = Get Gas D = Buy Beer at Liquor Store E = Open First Beer (While I Cook) F = Boil Potatoes G = Make Taquitos de Papas y Queso H = Enjoy Dinner with Girlfriend</p><p>Having established which tasks I need complete, I begin to determine an order of precedence because, as I recall, I cannot start task A or D until I complete task C, and I definitely cannot start E until I complete those. I come up with a partially ordered set <em>({A, B, C, D, E, F, G, H}, &lt;)</em> where <em>&lt;</em> represents a partial order relation based on my assessment of precedence. The contents of this poset is the following:</p><p>{(A, E), (B, H), (C, A), (C, D), (D, E), (E, B), (E, F), (F, G), (G, H)}</p><p>Reading the contents of the poset in set-builder notation makes it a little difficult to read and understand the full order of precedence of the tasks I need to complete. So, I can make a graph of the tasks and create directed edges using the ordered pairs in the poset. This produces the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/0*qjJctSoCDYx-G0gJ.png" /></figure><p>This helps illustrate that a directed acyclic graph is a partially ordered set. The graph contains nodes for each distinct task, and the directed edges are created from the elements of the poset. Closer examination also shows that there are no cycles prsent.</p><p>While an illustration of the graph makes it clear that there is an order of precedence to the tasks, it still does not provide us with a schedule that preserves this precedence; that is, we do not quite know in which exact order we should complete the tasks. For that, we need to understand total ordering and the topological sort.</p><h3>Total Ordering</h3><p>A <strong>total order</strong>, or <strong>linear order</strong>, is relation on a set similar to a partial order but with the added property of totality.</p><p>The property of <strong>totality</strong> states that every two elements from the poset <em>(S, ≼)</em> must be comparable. Remember that for two elements <em>a</em> and <em>b</em> to be comparable, it has to be the case that <em>a ≼ b</em> or <em>b ≼ a</em>.</p><p>Whereas a partial order may contain elements that are incomparable, the property of totality makes it so that every element within the set must be comparable to be considered as a totally ordered set. As a result, a totally ordered set is much more strict and produces a linear order compared to a partial order. This can be illustrated when you consider the poset <em>(ℤ, &lt;)</em>. This total order on the set of integers will produce a number line of the integers where it will be the case that <em>a &lt; b</em> or <em>b &lt; a</em> for any <em>a, b Є ℤ</em>.</p><p>We can illustrate this on a smaller, finite set, such as the totally ordered set <em>({-2, -1, 0, 1, 2}, &lt;)</em>, which contains the following elments:</p><p>{(-2, -1), (-1, 0), (0, 1), (1, 2)}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/0*i10x2iUqeE8416uP.png" /></figure><h3>A Total Ordering of a Poset</h3><p>The topological sort is a solution to scheduling problems, and it is built on the two concepts previously discussed: partial ordering and total ordering.</p><p>At its core, a <strong>topological sort</strong>, or a <strong>linear extension</strong>, is a total ordering of a partially ordered set.</p><p>We can arrive at this definition of a topological sort by first recalling what a directed acyclic graph is: it is a partial ordering of a set. In other words, a DAG is a partially ordered set, such as poset <em>T ({A, B, C, D, E, F, G, H}, ≤)</em> discussed earlier.</p><p>Again, recall the contents of this poset:</p><p>{(A, E), (B, H), (C, A), (C, D), (D, E), (E, B), (E, F), (F, G), (G, H)}</p><p>Performing a total ordering of the poset <em>T</em>, we can produce the following totally ordered set, which is one of many totally ordered sets:</p><p>{(C, A), (C, D), (A, E), (E, F), (F, G), (E, B), (B, H)}</p><p>The above totally ordered set can be distilled to clarify the following path through the graph:</p><p>C → A → D → E → F → G → B → H</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lHLZ7LJ1ivol9xfb.png" /></figure><p>And with this total ordering of the partially ordered set <em>T</em>, we have a valid schedule of tasks that preserve the order of precedence.</p><h4>Multiple Valid Totally Ordered Sets</h4><p>Note that there can be a number of different totally ordered sets. For example, another valid totally ordered set for poset T is the following:</p><p>{(C, D), (C, A), (D, E), (E, B), (E, F), (F, G), (G, H)}</p><p>Which produces the following schedule of tasks:</p><p>C → D → A → E → B → F → G → H</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xmubvYm9Vv_-SWak.png" /></figure><p>There can be a number of different topological orderings of a directed acyclic graph, but identifying them all has the potential to be very inefficient, as identifying and counting them all can grow exponentially to the size of the graph.</p><h3>Topological Sorting Algorithms</h3><p>The two common topological sorting algorithms are Kahn’s algorithm and a modified depth-first search. Because I challened myself to be familiar with them, an overview of both of the algorithms will be discussed with code samples in three languages: Kahn’s algorithm in Javascript and Java and the modified depth-first search in C#.</p><h3>Kahn’s Algorithm</h3><p>Kahn’s algorithm can be reduced to 4 main task, detailed below:</p><ol><li><em>Count and store the in-degrees of all nodes in a graph</em>. The <strong>in-degree</strong> of a node <em>A</em> is the number of edges that have <em>A</em> as the target or destination.</li><li><em>Identify nodes with an in-degree of 0. Add each node to a set that will be iterated over </em><strong><em>and</em></strong><em> append each node to a list that will contain the sorted nodes.</em></li><li><em>While the set containing nodes with an in-degree of 0 is not empty, remove a node. For each node removed, iterate over its edges, decrementing the stored in-degree of each destination node in the edge. If a node now has an in-degree of 0, add it to the set and list per step 2.</em></li><li><em>Finally, return the list each node is appended to. This will contain a topological ordering of the nodes.</em></li></ol><p>With minor adjustments to the input for my Javascript example, each code sample reads input from a file in the following format and with the following data, which reflects poset <em>T</em> in my example from earlier:</p><pre>9 8 0 4 1 7 2 0 2 3 3 4 4 1 4 5 5 6 6 7</pre><ol><li>The first line is the number <em>E</em> of edges in the graph.</li><li>The second line is the number <em>N</em> of nodes in the graph.</li><li>The last <em>E</em> lines are the edges, where the first number is the source node and the second number is the destination node.</li></ol><h3>Javascript Example of Kahn’s Algorithm</h3><p>The Javascript example of Kahn’s algorithm was constructed in three files for the sake of modularity.</p><p>First, I created a simple DirectedAcyclicGraph that just contains the bare-bones for what I needed:</p><pre>Find my code at <a href="https://davidurbina.blog/on-partial-order-total-order-and-the-topological-sort/">https://davidurbina.blog/on-partial-order-total-order-and-the-topological-sort/</a></pre><p>The next file contained Kahn’s Algorithm which accepts as input an adjacency set of a graph and the size of a graph.</p><pre>Find my code at <a href="https://davidurbina.blog/on-partial-order-total-order-and-the-topological-sort/">https://davidurbina.blog/on-partial-order-total-order-and-the-topological-sort/</a></pre><p>And lastly, the third file brings everything together. It directs Node to read from a file, construct the adjacency set, and call the function that performs Kahn’s Algorithm:</p><pre>Find my code at <a href="https://davidurbina.blog/on-partial-order-total-order-and-the-topological-sort/">https://davidurbina.blog/on-partial-order-total-order-and-the-topological-sort/</a></pre><p>Here is the screenshot of the console output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/0*2g1dDjCBLrcIpoP3.png" /></figure><p>This path, when translated to correspond with the nodes in poset <em>T</em> for the tasks in my dinner example, identifies the following valid topological path:</p><p>C → A → D → E → B → F → G → H</p><h3>Java Example of Kahn’s Algorithm</h3><p>The Java example is as follows:</p><pre>Find my code at <a href="https://davidurbina.blog/on-partial-order-total-order-and-the-topological-sort/">https://davidurbina.blog/on-partial-order-total-order-and-the-topological-sort/</a></pre><p>Here is the screenshot of the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/0*pALwL8xyaTPGaHSO.png" /></figure><p>The path, when translated, is the same as the one produced in the Javascript example:</p><p>C → A → D → E → B → F → G → H</p><h3>Modified Depth-First Search</h3><p>A depth-first traversal of a graph begins at a node <em>A</em> and exhaustively explores each branch before exploring the next branch.</p><p>A depth-first search can be modified to produce a topological sorting of a directed acyclic graph by placing nodes on a stack after their children have been exhaustively explored.</p><p>Examine the diagram below which illustrates a topological sorting of Poset <em>T</em> using a depth-first search.</p><p>Green numbers indicate the position in which a node is visited.</p><p>Blue numbers indicate the position in which a node is placed on the stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/0*dKI_3FxVvZrG1bJ2.png" /></figure><p>The topological sorting algorithm begins on node A. A depth-first traversal on it moves onto E, since its the only child of A.</p><p>E has two children. At this point, the algorithm can move on to either child and still produce a valid topological sorting, as long as it exhaustively explores each child before moving on to the next.</p><p>In this instance, the algorithm goes through this first path before placing any nodes on the stack:</p><p>After reaching <em>H</em>, which has no children, the depth-first traversal goes back up, placing <em>H</em> and then <em>B</em> on the stack as the first two elements.</p><p>With one child fully explored, <em>F</em>, the other child of <em>E</em> is explored, which results in placing <em>G</em> and <em>F</em> on the stack.</p><p>Having explored all of the children of <em>E</em>, it is placed on the stack followed by <em>A</em>.</p><p>Lastly, <em>C</em> is explored, which leads to <em>D</em>, the only unexplored child of <em>C</em>. <em>D</em> and <em>C</em> are then placed on the stack.</p><p>The nodes in poset <em>T</em> are placed in this order on the stack:</p><p>H → B → G → F → E → A → D → C</p><p>When the nodes are popped off the stack, we get this valid topological sorting:</p><p>C → D → A → E → F → G → B → H</p><h3>C# Example of Depth-First Search Topological Sort</h3><p>I created a DirectedAcyclicGraph class that contains the depth-first search topological sort algorithm:</p><pre>Find my code at <a href="https://davidurbina.blog/on-partial-order-total-order-and-the-topological-sort/">https://davidurbina.blog/on-partial-order-total-order-and-the-topological-sort/</a></pre><p>And here is the code that runs it:</p><pre>Find my code at <a href="https://davidurbina.blog/on-partial-order-total-order-and-the-topological-sort/">https://davidurbina.blog/on-partial-order-total-order-and-the-topological-sort/</a></pre><p>And here is a screenshot of the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*1i6BRjzBuZ8Uro_s.PNG" /></figure><h3>Conclusion</h3><p>Scheduling problems are bound to be encountered because they are commonly found disguised in the problems and challenges we encounter in every day life. That is one of the reasons why I was immediately drawn to topological sorting.</p><p>Because every scheduling problem will vary, I will leave it up to the reader to decide on whether to use Kahn’s algorithm or a modified depth-first search for their topological sorting needs. While my code examples are tailored to my specific example problem, implementations can nonetheless be derived from them to suit other scenarios.</p><h3>Afterthought</h3><p>I learned a lot through self-study in this endeavor, so if any errors or inconsistencies are found, please feel free to point them out so that I can revise them. I would absolutely appreciate it :)</p><p>Thank you for reading.</p><p><em>Originally published at </em><a href="https://davidurbina.blog/on-partial-order-total-order-and-the-topological-sort/"><em>davidurbina.blog</em></a><em> on September 29, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f9c0d0d812f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Search and The AVL Tree]]></title>
            <link>https://medium.com/@WindUpDurb/on-binary-search-and-the-avl-tree-52b889b4e917?source=rss-2cf21ec322b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/52b889b4e917</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[graph-theory]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[David Urbina]]></dc:creator>
            <pubDate>Wed, 20 Sep 2017 00:00:00 GMT</pubDate>
            <atom:updated>2019-08-28T03:34:42.707Z</atom:updated>
            <content:encoded><![CDATA[<p>Binary search is a powerful search algorithm that has a worst-case performance in logarithmic time. In a list of 200,000 items, for example, a binary search will locate an item in at most 18 comparisons. But there is a very important condition for binary search to work correctly.</p><p>Binary search will only work on a sorted array of items. There wouldn’t be much to be concerned with if we imagine a sorted array that never changes. We could continually search the array in logarithmic time without worrying of ever having to interact with it in anything slower than <em>log n</em> time. But that’s not often the case. There are insertions and deletions into the array, and each operation must maintain the sorted order. There are also the infrequent adjustments to the size of an array if a dynamic array is used, even though it is still amortized to constant time. These operations, nonetheless, have at the very least linear worst-case time complexities because after an insertion or deletion, items either need to move forward to accommodate the new addition or move back to fill in a gap. And that — the maintenance of a sorted array — really offsets the power and efficiency of the binary search.</p><h3>Binary Search Trees</h3><p>A binary search tree is a tree data structure that addresses the issues that arise from the maintenance of a sorted array.</p><p>A binary search tree, for one, is a binary tree, as illustrated below, so each node in the tree has at most two children.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/0*YfsHp2afbuPNguFZ.png" /></figure><p>But as a binary search tree, it also has a special property that stores items so they can be efficiently retrieved and identified in sorted order. This property defines a binary search tree as satisfying the condition that any node <em>N</em> in the tree must be larger than or equal to its left child and smaller than its right child.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*l2TH8kkUrP5Fov_W.png" /></figure><p>On average, a binary search tree will have logarithmic time insertion and deletion operations to match the <em>log n</em> time it takes to search for an item. But that is an average time complexity, not a worst-case time complexity.</p><p>Imagine a scenario where items were inserted into a binary search tree in ascending order such as, for example, the set <em>{1, 2, 3, 4, 5}</em>. How will this binary search tree look?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/0*HBjrWYueSs_rw8HS.png" /></figure><p>In this scenario, the binary search tree would have devolved into a list which would degenerate the search, insertion, and deletion operations to a slower linear time complexity. Keep in mind that a binary search tree is a linked data structure unlike an array, which is a contiguous data structure. So by devolving into a linked list, maintenance and operations on the binary search tree will be worse than a sorted array, as searching will basically be a linear search.</p><p>To ensure the search, insertion, and deletion operations of a binary search tree remain in logarithmic time, a condition must be met and maintained: the binary search tree must be balanced.</p><h3>AVL Tree</h3><p>The AVL tree, named after its inventors Georgy Adelson-Velsky and Evgenii Landis, is one of the two more commonly used <strong>self-balancing binary search trees</strong>, with the other being a red-black tree. While the red-black tree is the more widely taught self-balancing binary search tree, the AVL tree does possess some benefits over the red-black tree, so it is worth studying.</p><p>The self-balancing nature of the AVL tree is derived from the balance factor in each node of the tree, which is defined as the height of a node’s right sub-tree subtracted by the height of the node’s left sub-tree.</p><p>Pseudocode BalanceFactor(Node) = Height(Node.RightChild) — Height(Node.LeftChild)</p><p>To be considered an AVL tree, every node must have a balance factor inclusively between -1 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*jdHgdDu84PEnJCPF.png" /></figure><p>If the balance factor of a node is less than or equal to -1, it is considered <strong>left-heavy</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*YF7IaHeTpbYuKcb-.png" /></figure><p>If the balance factor of a node is more than or equal to 1, it is considered <strong>right-heavy</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*uD1GYJmG9rUfQGNB.png" /></figure><p>If the right-heaviness or left-heaviness of a node goes lower than -1 or above 1, then the AVL tree loses its balance and re-balances to maintain itself as a proper AVL tree.</p><h3>AVL Tree Rotations</h3><p>An AVL tree re-balances itself by performing either a <strong>right rotation</strong> and/or a <strong>left rotation</strong> in one of four unbalanced scenarios.</p><h3>Single Rotations</h3><p>A straight left-heavy imbalance can occur in a node <em>N</em> when it has a balance factor less than -1 and its left child is left-heavy. This is illustrated by a diagonal line, specifically one with a positive slope where the line is ascending, as depicted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/0*0zzAhuDA_b7Acn8O.png" /></figure><p>A right rotation is performed in this instance when a node <em>N</em> has a balance factor less than -1 and its left child is left-heavy. This operation is illustrated below, where node 24 replaces node 26, making 26 the right child of 24.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/0*IxaVsNOR_Qj5dQGN.png" /></figure><p>Inversely, a straight right-heavy imbalance can occur in a node <em>N</em> when its right child is right-heavy. This imbalance is also illustrated by a diagonal line, but of one with a negative slope where the line is descending, as depicted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/0*hBYbcLhBkzoYQzVq.png" /></figure><p>In this case, the offending node has a balance factor of 2 and its right child is right-heavy, which prompts the AVL tree to perform a left rotation. Node 28 replaces node 24, making 24 the left child of 28.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/0*0RWVoZ51Ewu5-IGs.png" /></figure><h3>Double Rotations</h3><p>A zigzag left-heavy imbalance can occur in a node <em>N</em> when it has a left-heavy imbalance and its left child is right-heavy. This imbalance will be illustrated by a zigzag that opens to the right, as depicted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/0*jYsQ7dH1S5JBgWDN.png" /></figure><p>To address this imbalance, a <strong>left-right rotation</strong> will be performed which is a left rotation followed by a right rotation.</p><p>First, the left rotation is performed which transforms the zigzag left-heavy imbalance into a straight line left-heavy imbalance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/0*Vpd_A3nTGf6-OJH1.png" /></figure><p>And as described earlier, the right rotation clears the imbalance, balancing the AVL tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/0*WoiWcTZEmrydtOU9.png" /></figure><p>The last scenario is a zigzag right-heavy imbalance. This occurs when a node <em>N</em> has a right-heavy imbalance and its right child is left-heavy. This imbalance is also illustrated by a zigzag, but it opens to the left, as depicted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/0*Usotg5MHdjaZkNeA.png" /></figure><p>This imbalance is addressed by a <strong>right-left rotation</strong>, which is a right rotation followed by a left rotation.</p><p>First, the right rotation is performed to transform the zigzag right-heavy imbalance into a straight line right-heavy imbalance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/0*BPLHLQ_ozGk3cjpE.png" /></figure><p>And lastly, a left rotation clears the imbalance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*zS46McH08WtbLhFJ.png" /></figure><h3>AVL Tree Overview</h3><p>Because the balance of an AVL tree is strictly maintained following insertions and deletions, the AVL tree will always have a swift and efficient look-up in logarithmic time. While the red-black tree also has a <em>O(log n)</em> time complexity for searches like the AVL tree, it does perform a tad bit slower than the AVL tree, and I’ll explore this in a post on red-black trees.</p><p>But compared to the red-black tree, insertion and deletions operations in an AVL tree are a touch slower. This is in exchange for the quicker searches, and it is derived from the rotation operations that occur more frequently in the AVL tree than the red-black tree, as the more frequent rotations preserve a stricter balance.</p><p>So, an AVL tree is favored in scenarios where the frequency of search operations outweigh the frequency of insertion and deletion operations.</p><p>Nonetheless, the AVL tree, like the red-black tree, still has a <em>O(log n)</em> time complexity for search, insertion, and deletion operations.</p><h3>AVL Tree Versus Sorted Array</h3><p>I coded a time trial to illustrate the difference between using a sorted array and a self-balancing binary search tree, namely and AVL tree, to perform efficient searches on.</p><p>I built a DynamicArray class in C# that resizes the underlying array of the class by creating a new array of size <em>2n</em> when the original <em>n</em>-sized array becomes full. This is followed by copying the contents of the original array into the new larger array.</p><p>In addition, insertion into the dynamic array maintains a sorted order, so items in the array are moved back to accommodate the new insertion.</p><p>The DynamicArray class also has a binary search method that uses the C# <em>Array.BinarySearch</em> method to search for an item.</p><p>The AVLTree class that I built contains all the basic operations for an AVL tree, including insertion and search. It also contains a PrintTree method that performs an in-order traversal to print the tree in sorted order.</p><p>The time trial consists of adding 25,000 items to the structure. Every 10 items a binary search is performed. This is to simulate an environment that is insertion-heavy with the infrequent search.</p><p>Below is the results for the first trial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/0*NHq5PJe0Db9eqTS-.PNG" /></figure><p>Over the course of 5 trials, the average time for the DynamicArray class was 00:00:14.90 and the average time for the AVL tree was 00:00:01.40.</p><p>Here is the code for the DynamicArray class, AVLTree class, and the time trial:</p><pre>Find my code on my blog at <a href="https://davidurbina.blog/on-binary-search-and-the-avl-tree/">https://davidurbina.blog/on-binary-search-and-the-avl-tree/</a></pre><h3>Conclusion</h3><p>As the time trial illustrates, the choice of data structures plays an important role for the overall performance of a program. Yes, the binary search will always have a worst-case time complexity in logarithmic time for both a sorted array and an AVL tree. But algorithmic choices — such as choosing a binary search — are but just one important fundamental aspect of software design.</p><p>The choice of data structure is another important fundamental aspect of software design. While binary search will have that <em>O(log n)</em> time complexity, choosing an array as the underlying data structure to perform the algorithm on will require maintenance that detracts heavily from the logarithmic time benefits of binary search, especially when compared to a self-balancing binary search tree.</p><p>If there is one conclusion to take away, it is to be mindful and conscious of the needs of the software you are building. Keep in mind not just the algorithms you’re building or using, but the data structures — and especially, how the data structures and algorithms interact with each other. For all you know, the sweet logarithmic time you sought might be getting buried under linear time operations.</p><p><em>Originally published at </em><a href="https://davidurbina.blog/on-binary-search-and-the-avl-tree/"><em>davidurbina.blog</em></a><em> on September 20, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52b889b4e917" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introductory Overview of Dijkstra’s Algorithm]]></title>
            <link>https://medium.com/@WindUpDurb/an-introductory-overview-of-dijkstras-algorithm-43bd10199e3b?source=rss-2cf21ec322b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/43bd10199e3b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[graph-theory]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[David Urbina]]></dc:creator>
            <pubDate>Tue, 12 Sep 2017 23:16:16 GMT</pubDate>
            <atom:updated>2017-10-06T00:37:34.167Z</atom:updated>
            <content:encoded><![CDATA[<p>Dijkstra’s algorithm was perhaps the first algorithm that inspired me to pursue further self-study into algorithms, algorithm design, and algorithm analysis. Why? When I first discoverd it and attempted to understand it, the algorithm was frankly a little intimidating and somewhat ungraspable. But I was rather hasty and impatient in this initial pursuit. I approached it again and took the time to dissect it, and what I discoverd was that the meat of the logic behind the algorithm wasn’t complicated at all — and what was once intimidating collapsed into a beautifully simple pathfinding procedure that produces the shortest paths from a source node to every other node in a weighted graph</p><p>Dijkstra’s algorithm also helped to develop my appreciation and understanding of graphs, which is fundamental in understanding this algorithm. So, I open this post going over the basic background terms and concepts in graph theory that Dijkstra’s algorithm relies on.</p><h3>Background</h3><p>A <strong>graph</strong> is a data structure that models relationships between <strong>nodes</strong>, or <strong>vertices</strong>, which themselves often represent objects. A common, and effective, analogy for understanding graphs is a map. Take, for example, a map of bars between my home and a party my friend and I have to get to where each node within the graph represents either a bar, my home, or the party we have to get to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/0*GBnjM0X0rjzWBMdn.png" /></figure><p><strong>Edges</strong> connect nodes to one another, as illustrated through the web of lines between the nodes above. Pappy’s (node 3) and Kip’s (node 6) share an edge, for example, so these two nodes have a relationship with one another. The significance of that relationship is undefined at the moment, as the graph above is <strong>unweighted</strong>, but nonetheless, there is still a relationship between the two nodes.</p><p>The graph above can be more formally denoted as <em>G = (V, E)</em>, where graph G is an <em>ordered pair</em> consisting of a <em>set of verticies</em>, here denoted by V, and a <em>set of edges</em>, here denoted by E.</p><p>Edges in a graph can be attributed with a value, or a <strong>weight</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/0*r8wcP0JL3MKOCqMz.png" /></figure><p>Illustrated above is a <strong>weighted, undirected graph</strong> because although the edges are ascribed with a value — or, a weight — which is the number of miles between bars, there are no directions to the edges, so navigation between connected nodes goes both ways and the weight is applicable in both directions.</p><p>In this case, moving between Pappy’s and Kip’s is 1 mile, whether I’m going to Kip’s from Pappy’s or from Kip’s to Pappy’s.</p><p>More formally, the graph above is denoted as <em>G2 = (V2, E2)</em>. It contains the edge <em>(Pappy’s, Kip’s) ∈ E2</em>, which means that the <em>ordered pair (Pappy’s, Kip’s)</em> is an element of the set <em>E2</em>. The graph <em>G2 = (V2, E2)</em> is then understood to be undirected because edge <em>(Pappy’s, Kip’s) ∈ E2</em> implies that edge <em>(Kip’s, Pappy’s) ∈ E2</em>.</p><p>Using Dijkstra’s algorithm, I could figure out the most mile-efficient route I could take to our destination, the party my friend and I have to get to, stopping at each bar on the way. But that has little relevance to us at this moment. My buddy and I are more interested in getting a little buzz before the party with as little money as possible and only stopping at a bar for a drink each. So, I do some research and calculate how much it would cost for 2 drinks at each bar within the map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/0*_3WBuLtNJaVB_EJu.png" /></figure><p>Illustrated above is a graph <em>G3 = (V3, E3)</em>, and it is understood to be both <strong>weighted</strong> because the edges have a cost and <strong>directed</strong> because edge <em>(Home, Pappy’s) ∈ E3</em> does not imply that <em>(Pappy’s, Home)</em> is also in <em>E3</em>. In fact, <em>(Pappy’s, Home) ∉ E3</em>.</p><p>With direction attached to the edges in <em>G3</em>, navigation between connected nodes are restricted by the edge’s direction. For example, there are three edges connected to my Home (node 1), and they only extend out. So, I can only move outwards from Home, the <strong>source node</strong>, to either Rudolph’s, Pappy’s, or Surf Bar, the <strong>destination nodes</strong> in this relationship. I cannot navigate back home, since there are no directed edges pointing to it.</p><p>The weight of the edges above represents how much it would cost to get two drinks at the destination node. So, the edge connecting Kip’s, the source node, to Triple Rock, the destination node, has a weight of $12, which means that I can get 2 drinks at Triple Rock for $12. This is also illustrated in the edge connecting Rudolph’s to Triple Rock.</p><p>With this background information, let’s see how Dijkstra’s algorithm can be used produce the most cost-efficient route to the party from my home, so that my buddy and I can stop at a few bars along the way and get a decent buzz without spending a lot of money.</p><h3>Understanding Dijkstra’s Algorithm</h3><p>While there are a number of variations of Dijkstra’s algorithm, this discussion will focus on a variation that implements a priority queue, specifically a minimum priority queue.</p><p>A <strong>priority queue</strong> is basically a queue that organizes the elements within it based on a priority. It’s a useful data structure that supports the basic operations of insert, find minimum (or maximum), and delete minimum (or maximum). In this case, an element with the highest priority will have the lowest value, making it a min-priority queue, so at any given time, and assuming the priority queue has more than a single element inside it, the element with the lowest value within the collection will be at the front of the queue.</p><p>To summarize the workings of the min-priority queue implementation of Dijkstra’s algorithm, the algorithm works by keeping track of the lowest value for the path weight to a given node from the source node, updating the path weight to a given node when a lower value is found.</p><p>The algorithm does some initial setup work by placing every node within the graph into the priority queue, setting each node with a default of infinity, or the maximum value for an Integer, and creating an <strong>adjacency set</strong>, which contains mappings between a node and a set of its edges. This is followed by setting the path weight of the starting node to 0, bringing it to the front of the priority queue.</p><p>After this setup <strong>the meat of the algorithm is as follows</strong>:</p><p><strong>1)</strong> While there are nodes in the priority queue, <strong>2)</strong> dequeue a node, <strong>3a)</strong> and loop through the set of edges for the dequeued node.</p><p><strong>3a)</strong> For each destination node in the set of edges for the dequeued node, <strong>3b)</strong> compare the stored path value for the destination node with the path value for the dequeued node added with the weight of the edge connecting the dequeued node to the destination node. If the currently stored path value for the destination node is larger, then we know we found a shorter path to it via the dequeued node, <strong>4)</strong> so we update the path value for the destination node as the sum of the path value for the dequeued node and the weight of the edge connecting it to the destination node.</p><p>Updating a node’s path value will cause the priority queue to reorganize, shifting nodes, so that the node with the smallest path value is at the front of the queue.</p><p>These operations continue until the priority queue is empty: so, to reiterate, the node at the front of the queue is removed, its set of edges are looped over and the destination node of these edges are updated if necessary, and the priority queue is reorganized.</p><p>When the algorithm is finished, the weight of the shortest path to each node from the source node will be produced.</p><h3>Coding Dijkstra’s Algorithm</h3><p>I structured my implementation of Dijsktra’s algorithm to accept input in the following format, which is read from a text file. This format, by the way, is identical to the HackerRank challenge found and read <a href="https://www.hackerrank.com/challenges/dijkstrashortreach">here</a>:</p><pre>1 11 22 1 2 10 1 3 15 1 4 28 2 3 15 2 5 12 3 4 28 3 6 11 3 5 12 4 6 11 4 7 12 5 6 11 5 8 30 6 7 12 6 9 23 6 8 26 7 9 23 7 10 10 8 9 23 8 11 0 9 10 10 9 11 0 10 11 0 1</pre><p>The algorithm’s output is also identical to the format of the HackerRank challenge:</p><pre>10 15 28 22 26 38 52 49 48 48</pre><p>Here is the code, written in Java, which just contains the meat of the min-priority queue implementation of Dijkstra’s algorithm:</p><pre>Find my code at <a href="https://davidurbina.blog/an-introductory-overview-of-dijkstras-algorithm/">https://davidurbina.blog/an-introductory-overview-of-dijkstras-algorithm/</a></pre><h3>Analysis of Dijkstra’s Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*isQ9B9-KU1edsVXI.jpg" /></figure><p>Through my analysis, the meat of this Java implementation of Dijkstra’s algorithm runs in <em>O(V2E)</em> time where <em>V</em> is equal to the cardinality of the set of verticies and <em>E</em> is equal to the cardinality of the set of edges in the graph.</p><p>This isn’t the best implementation of Dijkstra’s algorithm, and its inefficiency draws primarily from the underlying implementation of the priority queue in Java. The biggest cause for this inefficiency stems from the Java priority queue not reordering itself when one of its elements is updated, which in this case happens when the path to a node is updated. So the reordering is forced by explictly removing the updated node from the priority queue which is a linear operation because the updated node may or may not be at the front of the queue. The updated node is then re-added to the priority queue in logarithmic, reordering it in the underlying heap of the Java priority queue. Despite this, this implementation is useful for understanding the meat of the logic in Dijkstra’s algorithm while using the Java tools available. With a thorough understanding of the logic of the algorithm, you can then move forward with a more efficient implementation.</p><p>If there are any errors in my analysis, please feel free to point them out. I’d be grateful for the review.</p><p><em>Originally published at </em><a href="https://davidurbina.blog/an-introductory-overview-of-dijkstras-algorithm/"><em>davidurbina.blog</em></a><em> on September 12, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43bd10199e3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>