<?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 Sky Xu on Medium]]></title>
        <description><![CDATA[Stories by Sky Xu on Medium]]></description>
        <link>https://medium.com/@skyxu_41122?source=rss-d9ea2c53c9b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kl7-DHS0_-kUlaEt.</url>
            <title>Stories by Sky Xu on Medium</title>
            <link>https://medium.com/@skyxu_41122?source=rss-d9ea2c53c9b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:57:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@skyxu_41122/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[Sorting through the universe (insertion sort, merge sort and quick sort) ‍]]></title>
            <link>https://medium.com/@skyxu_41122/sorting-through-the-universe-insertion-sort-merge-sort-and-quick-sort-cd72e208db04?source=rss-d9ea2c53c9b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd72e208db04</guid>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[logarithm]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Sky Xu]]></dc:creator>
            <pubDate>Mon, 19 Feb 2018 05:42:22 GMT</pubDate>
            <atom:updated>2018-03-26T21:35:15.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*FaE9TdkrpFSLH0gkL-yYnQ.gif" /><figcaption>From Giphy.com</figcaption></figure><p>Sorting a list of items into an order that suits your desire is kinda like the sorting hat in Hogwarts trying to find the best house for young witches. 🎩 It’s exciting, but could be a bit tricky to implement in an algorithm — like, how do we make sure that we are using the fastest method to sort, and how much space are we taking up in the memory storage of the sorting engine? We are gonna discuss all of the intricacies of those problems in this article. (Because of the readability of python, I’m using python to show examples of the code.)</p><h4>Insertion Sort 😐</h4><p>Insertion Sort is sorting given items by taking an unsorted item, inserting it in sorted order in front of the other items, and repeating until all items are in order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*kTKdcrt2bsQAVNDZ2KLi0w.gif" /><figcaption>Rainbow Insertion sort (from Morolin’s <a href="https://imgur.com/gallery/voutF">sorting algorithms visualized</a>)</figcaption></figure><pre>def insertion_sort(items):<br>    for i in range(0, len(items)-1):<br>        if items[i] &gt; items[i+1]:<br>            insert_item = items.pop(i)<br>            last_index = i<br>            for j in range(last_index-1):<br>                if items[j] &gt; insert_item:<br>                    items.insert(j, insert_item)</pre><p>Since we are only moving the smaller item in front without moving blocks of items, the whole process is relatively stable, and it would <strong><em>be O(n) time in the best case </em></strong>😃. However, since we are looping through the item, from the last sorted item to the end of the list, the <strong><em>average case running time would be O(n²)</em></strong>, which is not ideal at all 😰. Also, since we only rearrange the original array of items,<strong><em> the average memory storage space would only be O(1).</em></strong></p><p>So overall, selection sort would only be great for a <strong>nearly sorted list.</strong></p><h4><strong>Merge Sort 😍👍</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*oi8oXFRJKLT7VU3Bm3uy0A.gif" /><figcaption>Rainbow Merge sort (from Morolin’s <a href="https://imgur.com/gallery/voutF">sorting algorithms visualized</a>)</figcaption></figure><p>Merge sort is a classic <a href="https://en.wikipedia.org/wiki/Divide_and_conquer_algorithm">divide and conquer algorithm</a>. First, we need a function to <strong>divide </strong>a<strong> </strong>list into two equal length lists. Than, we are gonna sort the two lists separately, and finally, we need to have a function to merge the two sorted lists into a new list containing all items in sorted order.</p><ol><li><em>divide </em>(this is the main function , we use it to call <em>conquer </em>and <em>merge recursively</em>)</li></ol><pre>def split_sort_merge(items):<br>    mid = len(items) // 2<br>    items1 = items[:mid]<br>    items2 = items[mid:]<br>    insertion_sort(items1)<br>    insertion_sort(items2)<br>    items[:] = merge(items1, items2)</pre><p>Here, to reuse code, I’m calling insertion sort that we defined earlier to sort the two separate lists.</p><p>2. <em>merge</em></p><pre>def merge(items1, items2):<br>    merged_list = []<br>    l_index = 0<br>    r_index = 0<br>    while l_index &lt; len(items1) and r_index &lt; len(items2):<br>        if items1[l_index] &lt; items2[r_index]:<br>            merged_list.append(items1[l_index])<br>            l_index += 1<br>        elif items1[l_index] &gt; items2[r_index]:<br>            merged_list.append(items2[r_index])<br>            r_index += 1<br>        else:<br>            merged_list.append(items2[r_index])<br>            merged_list.append(items1[l_index])<br>            r_index += 1<br>            l_index += 1<br>    if l_index == len(items1):<br>        for i in range(l_index):<br>            merged_list.append(items2[i])<br>    elif r_index == len(items2):<br>        for i in range(r_index):<br>            merged_list.append(items2[i])<br>    return merged_list</pre><p>So we are iterating through the two lists and appending whatever is the smaller item to the empty list, after we are done with one list, we just append the items left in the other list to the empty list.</p><p>Since we keep dividing lists into two smaller lists at each recursive call, which gives it log(n) component, and at each stage we also compare through the items in the list to decide which one is smaller among the two halves, <strong><em>the average running time is O(n*log(n)) </em>👏</strong>. However, we are making a new list, so <strong><em>the memory storage space is O(n) </em>😐<em>.</em></strong></p><h4><strong>Quick Sort 😂👍😳</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Melef3HRWrye0HaoCHRYSw.gif" /><figcaption>Rainbow Quick sort (from Morolin’s <a href="https://imgur.com/gallery/voutF">sorting algorithms visualized</a>)</figcaption></figure><p>Quick sort is an algorithm that chooses a random pivot (in this case we start from the first item) and sorts items smaller than it to the left and items bigger than it to the right till all items are in sorted order.</p><pre>def quick_sort(items):<br>    pivot = items[0]<br>    lesser_list = []<br>    greater_list = []<br>    for i in range(1, len(items)):<br>        item = items[index]<br>        if item &lt;= pivot:<br>            lesser_list.append(item)<br>        else:<br>            greater_list.append(item)<br>        quick_sort(lesser_list)<br>        quick_sort(greater_list)<br>    items[:] = lesser_list + pivot + greater_list</pre><p>Since we are dividing an array into two halves in each stage, it has log(n) operation, and each partition loops through the whole array, taking O(n) time — so in total, <strong>t<em>he average running time is O(n*log(n)).</em></strong></p><p>Although it’s a space sorting algorithm, we are calling each operation recursively, so we have <strong>extra stack frames space</strong>:<em> log(n)</em>, hence,<strong> the <em>average space is O(log(n)).</em></strong></p><p>To reduce the risk of an unbalanced pivoting point, which may cause extra running time, I suggest that we choose the pivot to be a random index.</p><p><strong>😨☠️ Caution: Since it’s moving blocks of items during each operation, it’s highly unstable 😱, so, keep that in mind if your app requires the stability of data. Also, we should avoid using quick sort if it’s a nearly sorted list, cause it’s gonna loop through the list of items anyways </strong>🤷🏻<strong>.</strong>‍</p><p><strong>Best Practice 😃: Quick sort works really well with a list with only a few unique items, cause it would group similar items together fast and reduce the redundant comparison 🙌.</strong></p><p><em>If you liked this article, click the👏 so more people will see it here on Medium. Thx! ❤️💚💛</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd72e208db04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The magic of binary tree]]></title>
            <link>https://medium.com/@skyxu_41122/the-magic-of-binary-tree-508ae2f2c87f?source=rss-d9ea2c53c9b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/508ae2f2c87f</guid>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[application-development]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Sky Xu]]></dc:creator>
            <pubDate>Mon, 19 Feb 2018 00:20:26 GMT</pubDate>
            <atom:updated>2018-02-22T03:43:58.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Pj4_vbM3JKdD9cuki3c0pw.gif" /><figcaption>From giphy.com</figcaption></figure><h4>— What is a binary tree</h4><p><strong>binary search </strong>is an algorithm for finding a target number in a <em>sorted</em> list. Image we are building the find friend feature for Facebook, which is famous for it’s enormous user data base (2 billion people). We can use binary tree to store all the users in a merely 30 level binary tree. Pretty amazing, right? Let me explain how it actually works using python in this article.🔥</p><h4>— How elements in binary tree interact with each other</h4><p>First of all, we need to understand the data structure of the binary tree node before implementing the functions in tree.</p><ol><li>initialize the binary tree node class</li></ol><pre>def __init__(self, data):<br>        self.data = data<br>        self.left = None<br>        self.right = None</pre><p>2. check when the tree node ends by defining what a leaf is</p><pre>def is_leaf(self):<br>        return self.left == None and self.right == None</pre><p>3. check if the node has any branch (have at least one child)</p><pre>def is_branch(self):<br>        return self.left != None or self.right != None</pre><p>step 2 and 3 are gonna come really handy for the future functions without having to repeat the same line of codes over and over again, it’s also a good way to make your code more organized.</p><p>4. To get the measure of the node height, we need to get the number of edges of the longest downward path from this node to a child leaf node</p><pre>def height(self):<br>        if not self.is_leaf():<br>            right_height = 0<br>            left_height = 0<br>            if self.right != None:<br>            right_height = self.right.height()<br>            if self.left != None:<br>                left_height = self.left.height()<br>            return 1 + max(right_height, left_height)<br>        return 0</pre><p>We are calling the height() function recursively on the right and left node of the desired node, it would stop at the leave node which is decided by the self.is_leaf() function.</p><h4>— How to implement a binary tree</h4><p>Now that we are done with building the foundation of binary tree, let’s start implementing binary search tree! 💁</p><ol><li>Initiate binary search tree class</li></ol><pre>def __init__(self, items=None):<br>   &quot;&quot;&quot;Initialize this binary search tree and insert the given items.&quot;&quot;&quot;<br>        self.root = None<br>        self.size = 0<br>        if items is not None:<br>            for item in items:<br>                self.insert(item)</pre><p>2. Let’s insert items into the tree and get the party started! 🎊 🎉</p><pre>def _find_parent_node(self, item):<br>        node = self.root<br>        parent = None<br>        while node is not None:<br>            if item == node.data:<br>                return parent<br>            elif item &lt; node.data:<br>                parent = node<br>                node = node.left<br>            elif item &gt; node.data:<br>                parent = node<br>                node = node.right<br>        return parent</pre><pre>def insert(self, item):<br>        if self.is_empty():<br>            self.root = BinaryTreeNode(item)<br>            self.size += 1<br>        parent = self._find_parent_node(item)<br>        if item == parent.data:<br>            raise ValueError(&quot;item already in tree&quot;)<br>        elif item &lt; parent.data:<br>            parent.left = BinaryTreeNode(item)<br>        elif item &gt; parent.data:<br>            parent.right = BinaryTreeNode(item)<br>        self.size += 1</pre><p>We are using the helper function _find_parent_node to loop through the tree from leave node to root node to get the parent node .</p><p>Since it’s a binary <strong>search</strong> tree, if the inserted item is equal to the parent data, which is retrieved through the helper function _find_parent_node , we are gonna raise a value error.</p><p>2. Search a certain item in tree</p><pre>def _find_node(self, item):<br>        node = self.root<br>        while node is not None:<br>            if node.data == item:<br>                return node<br>            elif node.data &gt; item:<br>                node = node.left<br>            elif node.data &lt; item:<br>                node = node.right<br>        return None</pre><pre>def search(self, item):<br>        node = self._find_node(item)<br>        return node.data</pre><p>First, we write a helper function to find the node that has the same data as item, then we call the function in search main function and return the node data.</p><p>3. Finally, we get to test out the magic of binary search tree by visiting each node of the tree!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*IKd10QPHMUy3gRk99vRG0g.gif" /><figcaption>From giphy.com</figcaption></figure><p>I’m going to demonstrate two different implementation to traverse the tree <strong>depth first search</strong>(<em>iteratively and recursively</em>) and <strong>breadth first search. </strong>You be the judge of which way works better for you.</p><h3><strong>1. depth first search</strong></h3><p>(DFS) is a method for exploring a tree or graph. In a DFS, you go as deep as possible down one path before backing up and trying a different one.<em>(quoted from interviewcake.com)</em></p><p><strong>Iteratively</strong>:</p><pre>from collections import deque</pre><pre>def _traverse_in_order_iterative(self, node, visit):<br>        node_stack = deque()<br>        node_stack.appendleft(node)<br>        while node_stack.length() &gt; 0:<br>             while node.left:<br>                # put left node in the front of the queue<br>                node_stack.appendleft(node.left)<br>                node = node.left<br>      # after going through all left leaves, look for right branches<br>             else:<br>                # pop out item from front if no more left<br>                node = node_stack.popleft()<br>                visit(node.data)<br>                # check right to see if it has left child node<br>                if node.right:<br>                    # append at front<br>                    node_stack.appendleft(node.right)<br>                    node = node.right<br>        return</pre><p>We are using python built in class deque (which is actually a double ended <em>queue data structure</em>) to append the node from the start of the queue and pop them out.</p><p>Since <strong>queue</strong> follows <strong>first in first out rule</strong>, we first put all the left nodes at the front of the queue, then root node, and finally the right nodes in the end of the queue, so the pop order is left, root, right.</p><p><strong>Big O Summary</strong>: <em>Because we are visiting each node from bottom to root, the memory storage and run time is both o(n), n being the number of nodes.</em></p><p><strong>Recursively</strong>:</p><pre>def _traverse_in_order_recursive(self, node, visit):<br>        if node.left:<br>            _traverse_in_order_recursive(node.left, visit)<br>        visit(node.data)<br>        if node.right:<br>            _traverse_in_order_recursive(node.right, visit)</pre><p><strong>Big O Summary</strong>: <em>Because the deepest call stack is height, so it’s only O(log2^n) memory storage space, same running time as iteratively method : O(n)</em></p><h3>2. <strong>breast first search (recursively)</strong></h3><p>(BFS) is a method for exploring a tree or graph. In a BFS, you first explore all the nodes one step away, then all the nodes two steps away, etc. <em>(quoted from interviewcake.com)</em></p><pre>def _traverse_level_order_iterative(self, start_node, visit):<br>        queue = deque()<br>        queue.append(start_node)<br>        while len(queue) &gt; 0:<br>            node = queue.popleft()<br>            visit(node.data)<br>            if node.left:<br>                queue.append(node.left)<br>            if node.right:<br>                queue.append(node.right)</pre><p>first, we visit the root node then enqueue every node’s left child, and then enqueue right child if exists. After that, we pop out each node from each level.</p><p><strong>Big O Summary</strong>: <em>Because the worst case memory storage space is the number of the nodes in base tree , which is half of the total nodes. memory storage: O(n), running time: O(n)</em></p><h3>— Conclusion: How to scale your app using binary tree</h3><p>(what’s good practice, what’s not)</p><p>If your app requires to search all N_order friends from your contact list, then we should use BFS to traverse, cause we want to organize data in different levels.</p><p>If your app doesn’t care about ordering data in levels, but it requires covering every depth of the data, then DFS might be your best choice. For example: GameTree uses DFS to organize gamers who are into the same game, so that they can put users in touch with like minded players.</p><p>Therefore, adapting your searching engine with what your application needs would be the best practice.</p><p>Thanks for reading.🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=508ae2f2c87f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>