<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ binary search - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ binary search - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 30 May 2026 22:26:03 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/binary-search/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Binary Search – Algorithm and Time Complexity Explained ]]>
                </title>
                <description>
                    <![CDATA[ When working with arrays, you’ll often have to search through them to check if they contain a target element. You can always run a sequential search—scanning the array from the beginning to the end—on the array. But if the array is sorted, running th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/binary-search-algorithm-and-time-complexity-explained/</link>
                <guid isPermaLink="false">66bb8b1a5d242388375d386e</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bala Priya C ]]>
                </dc:creator>
                <pubDate>Wed, 12 Jul 2023 14:26:58 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/cover-img-search.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When working with arrays, you’ll often have to search through them to check if they contain a target element.</p>
<p>You can always run a sequential search—scanning the array from the beginning to the end—on the array. But if the array is sorted, running the binary search algorithm is much more efficient.</p>
<p>Let's learn how binary search works, its time complexity, and code a simple implementation in Python.</p>
<h2 id="heading-how-does-linear-search-work">How Does Linear Search Work?</h2>
<p>We'll start our discussion with <strong>linear</strong> or <strong>sequential search</strong>.</p>
<p>Suppose we have an unsorted sequence of numbers <code>nums</code>. Given this nums array, you should check if the <code>target</code> is present in <code>nums</code>. You don’t have information about whether <code>nums</code> is sorted.</p>
<p>So the only way you can do this is to scan the array in a linear fashion, starting at the first element—until you find a match.</p>
<p>You can loop through the entire array to check if the element at index <code>i</code> matches the <code>target</code>. Once you find a match, you can break out of the loop.</p>
<p>Notice that in the worst case, you’ll have to scan the entire array and be lucky enough to find a match at the last index. Or you’ll have exhausted the array—without finding a match—indicating that the element is not present in the array. </p>
<p>Suppose the array has <code>n</code> elements. Because you have to scan the entire array—in the worst case—the linear search algorithm has a time complexity of O(n).</p>
<p>Here's an example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-66.png" alt="Image" width="600" height="400" loading="lazy">
<em>Linear Search Example | Image by the author</em></p>
<p>But when you do not know anything about the sequence, this is the best you can do. <em>So linear or sequential search is the best you can do when searching through unsorted sequences.</em></p>
<h3 id="heading-how-linear-search-works-in-python">How Linear Search Works in Python</h3>
<p>The function <code>linear_search</code> takes in an array <code>nums</code> and a <code>target</code> to search for. It then loops through the array sequentially to check if <code>target</code> is present in <code>nums</code>:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">linear_search</span>(<span class="hljs-params">nums,target</span>):</span>
  <span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> nums:
    <span class="hljs-keyword">if</span> num == target:
      <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
  <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
</code></pre>
<p>Here are a couple of sample outputs:</p>
<pre><code class="lang-python">nums = [<span class="hljs-number">14</span>,<span class="hljs-number">21</span>,<span class="hljs-number">27</span>,<span class="hljs-number">30</span>,<span class="hljs-number">36</span>,<span class="hljs-number">2</span>,<span class="hljs-number">5</span>,<span class="hljs-number">7</span>,<span class="hljs-number">11</span>]
target = <span class="hljs-number">27</span>

print(linear_search(nums,target))
<span class="hljs-comment"># Output: True</span>

target = <span class="hljs-number">100</span>
print(linear_search(nums,target))
<span class="hljs-comment"># Output: False</span>
</code></pre>
<h2 id="heading-how-does-binary-search-work">How Does Binary Search Work?</h2>
<p>Now consider the <code>nums</code> sequence with <code>n</code> elements sorted in ascending order. For any valid index <code>k</code>, the following holds <code>True</code> for the element <code>a_k</code> at index <code>k</code>:</p>
<blockquote>
<p>The elements at indices 0, 1, 2, …, (k-1) are all less than or equal to <code>a_k</code>. And all elements at indices (k+1) to (n-1) are greater than or equal to <code>a_k</code>.</p>
</blockquote>
<p>With this information, you no longer need to run a linear scan. You can do it much faster with binary search. </p>
<p>We’re given a sorted array <code>nums</code> and a <code>target</code>. Let mid denote the middle-most index of the array and <code>nums[mid]</code> denote the element at the middle index. Here’s how the binary search algorithm works:</p>
<ul>
<li>Check if <code>nums[mid]</code> is equal to the <code>target</code>. If so, we’ve already found a match—in the very first step—and the search terminates.</li>
<li>If <code>nums[mid]</code> &gt; <code>target</code>, you <em>only</em> need to search the <em>left half</em> of the array. Even when you search through the left subarray you can use the same binary search algorithm.</li>
<li>If <code>nums[mid]</code> &lt; <code>target</code>, you can ignore all the elements up to the middle element and <em>only</em> consider the <em>right half</em> of the array.</li>
</ul>
<p>Notice that we have a recurrence relation here. First, we start by running the binary search algorithm on the array with n elements. If we don't find the target in the very first step, we run binary search on the subarray of size at most n/2 elements.</p>
<p>If we end up with an empty array or an array with one element that is <em>not</em> the <code>target</code>, we conclude that the target does not exist in the <code>nums</code> array.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-65.png" alt="Image" width="600" height="400" loading="lazy">
<em>Binary Search Example | Image by the author</em></p>
<h3 id="heading-how-to-implement-binary-search-in-python">How to Implement Binary Search in Python</h3>
<p>Here's a recursive implementation of binary search in Python:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">binary_search</span>(<span class="hljs-params">nums,target,low,high</span>):</span>
  <span class="hljs-keyword">if</span> low &gt; high:
    <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
  <span class="hljs-keyword">else</span>:
    mid = (low + high)//<span class="hljs-number">2</span>
    <span class="hljs-keyword">if</span> nums[mid] == target:
      <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
    <span class="hljs-keyword">elif</span> nums[mid] &lt; target:
      <span class="hljs-keyword">return</span> binary_search(nums,target,mid+<span class="hljs-number">1</span>,high)
    <span class="hljs-keyword">else</span>:
      <span class="hljs-keyword">return</span> binary_search(nums,target,low,mid<span class="hljs-number">-1</span>)
</code></pre>
<p>With a few sample runs of the <code>binary_search</code> function:</p>
<pre><code class="lang-python">nums = [<span class="hljs-number">2</span>,<span class="hljs-number">5</span>,<span class="hljs-number">7</span>,<span class="hljs-number">11</span>,<span class="hljs-number">14</span>,<span class="hljs-number">21</span>,<span class="hljs-number">27</span>,<span class="hljs-number">30</span>,<span class="hljs-number">36</span>]
target = <span class="hljs-number">27</span>

print(binary_search(nums,target,<span class="hljs-number">0</span>,len(nums)<span class="hljs-number">-1</span>))
<span class="hljs-comment"># Output: True</span>

target = <span class="hljs-number">38</span>
print(binary_search(nums,target,<span class="hljs-number">0</span>,len(nums)<span class="hljs-number">-1</span>))
<span class="hljs-comment"># Output: False</span>
</code></pre>
<h2 id="heading-what-is-the-time-complexity-of-binary-search">What Is the Time Complexity of Binary Search?</h2>
<p>In binary search, we know that the <em>search space is reduced by half</em> at each step and this guides us in computing the time complexity. </p>
<p>For an array with <code>n</code> elements, we check if the middle-most element matches the <code>target</code>. If so, we return <code>True</code> and terminate the search.</p>
<p>But if the middle element does not match the <code>target</code>, we perform binary search on a subarray of size at most <code>n/2</code>. In the next step, we have to search through an array of size at most <code>n/4</code>. And we continue this recursively until we can make a decision in a constant time (when the subarray is empty). </p>
<p>At step <code>k</code>, we need to search through an array of size at most <code>n/(2^k)</code>. And we need to find the smallest such <code>k</code> for which we have no subarray to search through.</p>
<p>Mathematically:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-68.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The time complexity of binary search is, therefore, <strong>O(logn)</strong>. This is much more efficient than the linear time O(n), especially for large values of n.</p>
<p>For example, if the array has 1000 elements. 2^(10) = 1024. While the binary search algorithm will terminate in around 10 steps, linear search will take a thousand steps in the worst case.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>And that's a wrap. I hope you found this introduction to binary search helpful! You’ll often run into questions involving binary search in coding interviews. </p>
<p>If you’re preparing for coding interviews, check out <a target="_blank" href="https://youtu.be/Peq4GCPNC5c">10 Common Coding Interview Questions [Solved]</a> on freeCodeCamp’s YouTube channel.  </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Binary Search in C++ – Algorithm Example ]]>
                </title>
                <description>
                    <![CDATA[ The binary search algorithm is a divide and conquer algorithm that you can use to search for and find elements in a sorted array.  The algorithm is fast in searching for elements because it removes half of the array every time the search iteration ha... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/binary-search-in-c-algorithm-example/</link>
                <guid isPermaLink="false">66b0a27603036c3282dfd7c0</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Fri, 17 Mar 2023 16:52:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/binary-search-algorithm-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The binary search algorithm is a divide and conquer algorithm that you can use to search for and find elements in a sorted array. </p>
<p>The algorithm is fast in searching for elements because it removes half of the array every time the search iteration happens. </p>
<p>So instead of searching through the whole array, the algorithm removes half of the array where the element to be searched for can't be found. It does this continuously until the element is found. </p>
<p>In a case where the element to be searched for doesn't exist, it returns a value of -1. If the element exists, then it returns the index of the element. </p>
<p>If the explanations above seem complex, then you should check out this <a target="_blank" href="https://www.freecodecamp.org/news/binary-search-in-java-algorithm-example/#:~:text=How%20Does%20the%20Binary%20Search%20Algorithm%20Work%3F">visual guide on how the binary search algorithm works</a>. </p>
<p>In this article, you'll see an implementation of the binary search algorithm in C++.</p>
<p>Let's get started!</p>
<h2 id="heading-binary-search-algorithm-example-in-c">Binary Search Algorithm Example in C++</h2>
<p>In this section, we'll break down and explain the implementation of binary search in C++.</p>
<p>Here's the code:</p>
<pre><code class="lang-c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">binarySearch</span><span class="hljs-params">(<span class="hljs-keyword">int</span> <span class="hljs-built_in">array</span>[], <span class="hljs-keyword">int</span> low, <span class="hljs-keyword">int</span> high, <span class="hljs-keyword">int</span> number_to_search_for)</span> </span>{

    <span class="hljs-keyword">while</span> (low &lt;= high) {
        <span class="hljs-keyword">int</span> mid = low + (high - low) / <span class="hljs-number">2</span>;

        <span class="hljs-keyword">if</span> (number_to_search_for == <span class="hljs-built_in">array</span>[mid]){
            <span class="hljs-keyword">return</span> mid;
        }

        <span class="hljs-keyword">if</span> (number_to_search_for &gt; <span class="hljs-built_in">array</span>[mid]){
            low = mid + <span class="hljs-number">1</span>;
        }

        <span class="hljs-keyword">if</span> (number_to_search_for &lt; <span class="hljs-built_in">array</span>[mid]){
            high = mid - <span class="hljs-number">1</span>;
        }

    }

  <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">int</span> arrayOfNums[] = {<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">7</span>,<span class="hljs-number">9</span>,<span class="hljs-number">10</span>,<span class="hljs-number">13</span>,<span class="hljs-number">20</span>};

  <span class="hljs-keyword">int</span> n = <span class="hljs-keyword">sizeof</span>(arrayOfNums) / <span class="hljs-keyword">sizeof</span>(arrayOfNums[<span class="hljs-number">0</span>]);

  <span class="hljs-keyword">int</span> result = binarySearch(arrayOfNums, <span class="hljs-number">0</span>, n - <span class="hljs-number">1</span>, <span class="hljs-number">13</span>);

  <span class="hljs-keyword">if</span> (result == <span class="hljs-number">-1</span>){
      <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Element doesn't exist in the array"</span>);
  }
  <span class="hljs-keyword">else</span>{
      <span class="hljs-built_in">printf</span>(<span class="hljs-string">"The index of the element is %d"</span>, result);
  }

  <span class="hljs-comment">// The index of the element is 5</span>
}
</code></pre>
<p>To start with, we created a method called <code>binarySearch</code> which had four parameters:</p>
<ul>
<li><code>array[]</code> represents the array to be searched through.</li>
<li><code>low</code> represents the first element of the array. </li>
<li><code>high</code> represents the last element of the array. </li>
<li><code>number_to_search_for</code> represents the number to be searched for in <code>array[]</code>. </li>
</ul>
<p>Next, we created a <code>while</code> loop that will run continuously until the search operation returns a value – either the index of the element or -1. </p>
<p>In the <code>while</code> loop:</p>
<p><code>mid</code> is used to represent the center/midpoint of the array: <code>int mid = low + (high - low) / 2;</code>.</p>
<p>The first <code>if</code> statement is executed if <code>mid</code> has the same value as the element to be searched for: </p>
<pre><code class="lang-c++"><span class="hljs-keyword">if</span> (number_to_search_for == <span class="hljs-built_in">array</span>[mid]){
    <span class="hljs-keyword">return</span> mid;
}
</code></pre>
<p>The second <code>if</code> statement moves the position of <code>low</code> to the index after the midpoint of the array:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">if</span> (number_to_search_for &gt; <span class="hljs-built_in">array</span>[mid]){
    low = mid + <span class="hljs-number">1</span>;
}
</code></pre>
<p>This removes all the elements on the left side of the array because the element to be searched for is greater than they are, so there is no need to search through that part of the array.</p>
<p>The third <code>if</code> statement does the opposite of the second statement – it moves the position of high to the index before the midpoint of the array: </p>
<pre><code class="lang-c++"><span class="hljs-keyword">if</span> (number_to_search_for &lt; <span class="hljs-built_in">array</span>[mid]){
    high = mid - <span class="hljs-number">1</span>;
}
</code></pre>
<p>Here's a summary of the code in the <code>if</code> statements: </p>
<ol>
<li>If the number to be searched for is equal to <code>mid</code>, the <code>mid</code> index will be returned.</li>
<li>If the number to be searched for is greater than <code>mid</code>, search through the elements on the right side of <code>mid</code>.</li>
<li>If the number to be searched for is less than <code>mid</code>, search through the elements on the left side of <code>mid</code>.</li>
</ol>
<p>If the number to be searched for doesn't exist, -1 will be returned. You can see this after the <code>while</code> loop in the code. </p>
<p>Lastly, we tested the <code>binarySearch</code> method:</p>
<pre><code class="lang-c++"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">int</span> arrayOfNums[] = {<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">7</span>,<span class="hljs-number">9</span>,<span class="hljs-number">10</span>,<span class="hljs-number">13</span>,<span class="hljs-number">20</span>};

  <span class="hljs-keyword">int</span> n = <span class="hljs-keyword">sizeof</span>(arrayOfNums) / <span class="hljs-keyword">sizeof</span>(arrayOfNums[<span class="hljs-number">0</span>]);

  <span class="hljs-keyword">int</span> result = binarySearch(arrayOfNums, <span class="hljs-number">0</span>, n - <span class="hljs-number">1</span>, <span class="hljs-number">13</span>);

  <span class="hljs-keyword">if</span> (result == <span class="hljs-number">-1</span>){
      <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Element doesn't exist in the array"</span>);
  }
  <span class="hljs-keyword">else</span>{
      <span class="hljs-built_in">printf</span>(<span class="hljs-string">"The index of the element is %d"</span>, result);
  }

  <span class="hljs-comment">// The index of the element is 5</span>
}
</code></pre>
<p>In the code above, we passed in the values of the parameters created in the <code>binarySearch</code> method: <code>binarySearch(arrayOfNums, 0, n -1, 13)</code>. </p>
<ul>
<li><code>arrayOfNums</code> represents the array to be searched for: {2,4,7,9,10,13,20}. </li>
<li><code>0</code> represents the first index of the array. </li>
<li><code>n - 1</code> represents the last index of the array. Have a look at the code to see how <code>n</code> was created. </li>
<li><code>13</code> is the number to be searched for in <code>arrayOfNums</code>.</li>
</ul>
<p>When you run the code, "The index of the element is 5" will be printed in the console. This is because the index of the number to be searched for (13) is 5. </p>
<p>You can play around with the code by changing the value of the number to be searched for.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about the implementation of the binary search algorithm in C++. </p>
<p>We saw a code example that had a <code>binarySearch</code> method which took in parameters, searched through an array of numbers, and returned the appropriate value after the search operation. </p>
<p>We also saw a detailed explanation of each part of the code. </p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Binary Search in Java – Algorithm Example ]]>
                </title>
                <description>
                    <![CDATA[ Algorithms provide step by step instructions on solving specific problems. They help you solve problems using efficient, standard, and reusable steps.  The binary search algorithm is one of the commonly used algorithms in programming. It is used to s... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/binary-search-in-java-algorithm-example/</link>
                <guid isPermaLink="false">66b0a279d7edba94d20b3ba6</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Wed, 08 Mar 2023 22:26:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/binary-search-algorithm.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Algorithms provide step by step instructions on solving specific problems. They help you solve problems using efficient, standard, and reusable steps. </p>
<p>The binary search algorithm is one of the commonly used algorithms in programming. It is used to search and find an element in a sorted array. </p>
<p>The binary search algorithm is different from the <a target="_blank" href="https://www.freecodecamp.org/news/binary-search-tree-traversal-inorder-preorder-post-order-for-bst/">binary search tree</a>. We'll talk about their differences later in this article.</p>
<p>In this article, you'll learn how the binary search algorithm works with the aid of diagrams and code examples. </p>
<p>You'll see how to implement the algorithm in your Java program. </p>
<h2 id="heading-how-does-the-binary-search-algorithm-work">How Does the Binary Search Algorithm Work?</h2>
<p>In this section, you'll see a practical application of binary search using diagrams.</p>
<p>The binary search algorithm is a divide and conquer algorithm that searches for a specific element in a sorted array. </p>
<p>Note that the collection of elements/array must be sorted for the algorithm to work efficiently. </p>
<p>Here are the steps involved with the binary search algorithm:</p>
<h3 id="heading-step-1-sort-the-array">Step #1 - Sort the Array</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/sorted-array-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In order to start the search, you'll need to have a sorted array. The image above has a collection of numbers sorted in ascending order: 2,3,6,8,9,13,20.</p>
<p>Let's assume that the element we're looking for is 13. We'll store this in a variable called <code>number_to_search_for</code>.</p>
<h3 id="heading-step-2-choose-low-and-high-values">Step #2 - Choose Low and High Values</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/sorted-array-low-and-high-arrow.png" alt="Image" width="600" height="400" loading="lazy">
<em>sorted array with low and high pointers</em></p>
<p>The first index of the array will be denoted as <code>low</code> while the highest index will be denoted as <code>high</code>. </p>
<p>These values will help you get the <code>midpoint</code> of the array. </p>
<p>Midpoint = (low + high) / 2.</p>
<h3 id="heading-step-3-choose-midpointmiddle-element">Step #3 - Choose Midpoint/Middle Element</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/sorted-array-midpoint.png" alt="Image" width="600" height="400" loading="lazy">
<em>sorted array with low, high, and middle pointers</em></p>
<p>The image above shows the <code>midpoint</code> which is at the center of the array. </p>
<p>Now that you know the <code>low</code>, <code>high</code>, and <code>midpoint</code> of the array, the binary search operation can begin. </p>
<h3 id="heading-step-4-binary-search">Step #4 - Binary Search</h3>
<p>This is what happens during the binary search:</p>
<ol>
<li>If <code>number_to_search_for</code>  is equal to <code>midpoint</code>, the <code>midpoint</code> index will be returned. </li>
<li>If <code>number_to_search_for</code> is greater than <code>midpoint</code>, search through the elements on the right side of the <code>midpoint</code>.</li>
<li>If <code>number_to_search_for</code> is less than <code>midpoint</code>, search through the elements on the left side  <code>midpoint</code>. </li>
</ol>
<p>Step 3 will only be relevant if step 2 is false. If  <code>number_to_search_for</code> doesn't exist in the array, return -1. </p>
<p>Let's simplify the steps above using diagrams:</p>
<p>This is the array we're working with: 2,3,6,8,9,13,20. </p>
<p><code>number_to_search_for</code> = 13.</p>
<p><code>midpoint</code> = 8.</p>
<p><code>low</code> = 2.</p>
<p><code>high</code> = 20.</p>
<h3 id="heading-iteration-1">Iteration #1</h3>
<p>From the steps listed above, you begin by comparing <code>number_to_search_for</code> to <code>midpoint</code>. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/sorted-array-midpoint-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>sorted array with low, high, and middle pointers</em></p>
<p>As you can see in the diagram above, the value of <code>number_to_search_for</code> and <code>midpoint</code> are not the same. </p>
<p>The next step is to find out if the <code>number_to_search_for</code> is greater than or less than <code>midpoint</code>. </p>
<p>In our own case, it is greater than <code>midpoint</code> so we'll focus on the elements on the right side of the <code>midpoint</code> — 9, 13, and 20.</p>
<p>This makes the search much faster because we've cut out half of the array that isn't needed.</p>
<p>We'll repeat all the steps for those elements as well. </p>
<p>The steps will run continuously until the element is found. In a case where the element doesn't exist, -1 will be returned. </p>
<h3 id="heading-iteration-2">Iteration #2</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/sorted-array-low-and-high-arrow-iteration2.png" alt="Image" width="600" height="400" loading="lazy">
<em>sorted array with low, high, and middle pointers</em></p>
<p>Comparing the <code>midpoint</code> and <code>number_to_search_for</code> in the diagram above, we have the same value.</p>
<p>At this point, the binary search operation stops because we've found the number. The index of the number will be returned. </p>
<p>That is: index 5 from the original array (2,3,6,8,9,13,20). </p>
<p>In the next section, you'll see how to implement the algorithm in Java. </p>
<h2 id="heading-binary-search-algorithm-example-in-java">Binary Search Algorithm Example in Java</h2>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BinarySearch</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">binarySearch</span><span class="hljs-params">(<span class="hljs-keyword">int</span> numArray[], <span class="hljs-keyword">int</span> number_to_search_for)</span> </span>{
        <span class="hljs-keyword">int</span> low = <span class="hljs-number">0</span>;
        <span class="hljs-keyword">int</span> high = numArray.length - <span class="hljs-number">1</span>;

        <span class="hljs-keyword">while</span> (low &lt;= high){
            <span class="hljs-keyword">int</span> middleIndex = (low + high) / <span class="hljs-number">2</span>;
            <span class="hljs-keyword">int</span> middleIndexNumber = numArray[middleIndex];

            <span class="hljs-keyword">if</span> (number_to_search_for == middleIndexNumber){
                <span class="hljs-keyword">return</span> middleIndex;
            }
            <span class="hljs-keyword">if</span> (number_to_search_for &lt; middleIndexNumber){
                high = middleIndex - <span class="hljs-number">1</span>;
            }
            <span class="hljs-keyword">if</span> (number_to_search_for &gt; middleIndexNumber){
                low = middleIndex + <span class="hljs-number">1</span>;
            }
        }

        <span class="hljs-keyword">return</span> -<span class="hljs-number">1</span>;
  }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String args[])</span> </span>{

        <span class="hljs-keyword">int</span>[] arrayofnums = {<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">6</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">13</span>,<span class="hljs-number">20</span>};

        System.out.println(binarySearch(arrayofnums, <span class="hljs-number">13</span>));
        <span class="hljs-comment">// 5</span>

    }

}
</code></pre>
<p>In the code above, we created a method called <code>binarySearch</code> with two parameters — <code>int numArray[]</code> and <code>int number_to_search_for</code>: </p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">binarySearch</span><span class="hljs-params">(<span class="hljs-keyword">int</span> numArray[], <span class="hljs-keyword">int</span> number_to_search_for)</span></span>{...}
</code></pre>
<p>The first parameter represents the array to be searched through. The second represents the number to be searched for.</p>
<p>Next, we defined the <code>low</code> and <code>high</code> variables to represent the first and last index of the array: </p>
<pre><code class="lang-java"><span class="hljs-keyword">int</span> low = <span class="hljs-number">0</span>;
<span class="hljs-keyword">int</span> high = numArray.length - <span class="hljs-number">1</span>;
</code></pre>
<p>After that, we created a <code>while</code> loop with <code>if</code> statements matching the 3 steps used in the previous section (Step #4 - Binary Search section): </p>
<pre><code class="lang-java"><span class="hljs-keyword">while</span> (low &lt;= high){
    <span class="hljs-keyword">int</span> middleIndex = (low + high) / <span class="hljs-number">2</span>;
    <span class="hljs-keyword">int</span> middleIndexNumber = numArray[middleIndex];

    <span class="hljs-keyword">if</span> (number_to_search_for == middleIndexNumber){
        <span class="hljs-keyword">return</span> middleIndex;
    }
    <span class="hljs-keyword">if</span> (number_to_search_for &lt; middleIndexNumber){
        high = middleIndex - <span class="hljs-number">1</span>;
    }
    <span class="hljs-keyword">if</span> (number_to_search_for &gt; middleIndexNumber){
        low = middleIndex + <span class="hljs-number">1</span>;
    }
}
</code></pre>
<p>You can have a look at the <strong>Step #4 - Binary Search</strong> section to understand the code in the <code>while</code> loop. </p>
<p>We then returned -1 after the <code>while</code> loop in case the number being searched for doesn't exist in the array.</p>
<p>Lastly, we tested the method to be sure the functionality worked as expected:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String args[])</span> </span>{

     <span class="hljs-keyword">int</span>[] arrayofnums = {<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">6</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">13</span>,<span class="hljs-number">20</span>};

     System.out.println(binarySearch(arrayofnums, <span class="hljs-number">13</span>));
     <span class="hljs-comment">// 5</span>

}
</code></pre>
<p>We specified 13 as the second parameter and got index 5 returned. </p>
<p>If you use a number that doesn't exist in the array, you'll get -1 returned. </p>
<h2 id="heading-differences-between-binary-search-algorithm-and-binary-search-tree">Differences Between Binary Search Algorithm and Binary Search Tree</h2>
<p>Although both binary search algorithm and binary search tree are both used for searching, there are some differences in mode operation of operation and data structure. </p>
<p>Here are some differences:</p>
<ul>
<li><strong>Binary search algorithm</strong> is used for searching while <strong>binary search tree</strong> is used for searching, insertion, and deletion.</li>
<li><strong>Binary search algorithm</strong> compares the middle element with the element being searched for while <strong>binary search tree</strong> compares the value of nodes in a tree. </li>
<li><strong>Binary search algorithm</strong> searches through an array or list while <strong>binary search tree</strong> traverses through a tree of nodes.</li>
</ul>
<p>You can read more about the binary search tree <a target="_blank" href="https://www.freecodecamp.org/news/binary-search-tree-traversal-inorder-preorder-post-order-for-bst/">here</a>.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about the binary search algorithm. It is to search for specific elements in an array. </p>
<p>We saw how the algorithm works using visual guides. Then we saw an implementation of the algorithm in Java.</p>
<p>Lastly, we saw the differences between binary search algorithm and binary search tree. </p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Binary Search in Python – How to Code the Algorithm with Examples ]]>
                </title>
                <description>
                    <![CDATA[ In our daily lives, we're constantly searching for information or trying to find solutions to problems we encounter. When going through search results on the web, we pick the most relevant articles or resources that we think will help us. Search is s... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/binary-search-in-python-with-examples/</link>
                <guid isPermaLink="false">66d4614a55db48792eed3f9d</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tantoluwa Heritage Alabi NB ]]>
                </dc:creator>
                <pubDate>Mon, 18 Jul 2022 16:53:41 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/pexels-pixabay-277593.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In our daily lives, we're constantly searching for information or trying to find solutions to problems we encounter.</p>
<p>When going through search results on the web, we pick the most relevant articles or resources that we think will help us.</p>
<p>Search is such a part of our lives because we cannot always have the answers. And there are various algorithms that help programs run more efficiently and deal with data more effectively.</p>
<h2 id="heading-what-well-cover-in-this-tutorial">What We'll Cover in This Tutorial</h2>
<ul>
<li><p>What is a Search Algorithm?</p>
</li>
<li><p>What is a Binary Search algorithm?</p>
</li>
<li><p>How Binary Search Works – Divide and Conquer</p>
</li>
<li><p>Processes involved in Binary Search Algorithms</p>
</li>
<li><p>Methods Used in Binary Search Algorithms</p>
</li>
<li><p>Real-life examples of Binary Search</p>
</li>
</ul>
<h2 id="heading-what-is-a-search-algorithm">What is a Search Algorithm?</h2>
<p>A search algorithm works to retrieve items from any data structure. It compares the data that comes in as input to the information stored in its database and brings out the result. An example is finding your best friend’s number in your contact list of 1,000 numbers.</p>
<p>There are different types of search algorithms. Some of them are:</p>
<h3 id="heading-linear-search-algorithms">Linear search algorithms</h3>
<p>Linear search algorithms are the simplest of all the search algorithms. As the name implies, they operate in a sequence.</p>
<p>Linear search checks elements in a list one after the other to find a particular key value. This key value is among other items in the list and the algorithm returns the position by going through the check.</p>
<h3 id="heading-dijkstras-algorithm">Dijkstra's algorithm</h3>
<p>Dijkstra's shortest path algorithm is used in more advanced searches. Dijkstra’s algorithm maps out the shortest distance between two nodes. These nodes are often route networks.</p>
<p>This type of search is useful when you're trying to find routes on maps. It gives you options based on finding the shortest path possible.</p>
<h3 id="heading-binary-search-algorithm">Binary Search Algorithm</h3>
<p>Binary search algorithms are also known as half interval search. They return the position of a target value in a sorted list.</p>
<p>These algorithms use the “divide and conquer” technique to find the value's position.</p>
<p>Binary search algorithms and linear search algorithms are examples of simple search algorithms.</p>
<p>In binary search, the middle element in the list is found before comparing with the key value you are searching for. But in linear search, the elements are taken one by one in the list by looping through and comparing with the key value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/differences-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>‌During Binary search, the list is split into two parts to get the middle element: there is the left side, the middle element, and the right side.</p>
<p>The left side contains values smaller than the middle element and the right side contains values that are greater than the middle element. This method uses a sorted list to work.</p>
<p>A sorted list has its items arranged in a particular order. To make search efficient for binary search, the values in the list have to be arranged in the right order to satisfy the process of search. If a list has its values mixed up, it has to be sorted by a sorting algorithm before you perform the search.</p>
<h3 id="heading-sorting-algorithms">Sorting algorithms</h3>
<p>Sorting algorithms accept an unsorted list as an input and return a list with the elements arranged in a particular order (mostly ascending order).</p>
<p>There are <a target="_blank" href="https://www.freecodecamp.org/news/sorting-algorithms-explained-with-examples-in-python-java-and-c/">different types of sorting algorithms</a>, like insertion sort, quick sort, bubble sort, and merge sort.</p>
<h2 id="heading-how-binary-search-works-divide-and-conquer">How Binary Search Works – Divide and Conquer</h2>
<p>A binary search algorithm uses a technique called “divide and conquer” to tackle its task. The merge sort algorithm employs the same technique to sort items in a list.</p>
<p>In binary search algorithms, the “divide and conquer” method works this way:</p>
<ul>
<li><p>The algorithm splits the list into two parts: the left side and right side, separated by the middle element</p>
</li>
<li><p>It creates a variable to store the value of the item to be searched for</p>
</li>
<li><p>It picks out the middle element and compares it with the item to be searched</p>
</li>
<li><p>If the items compared are equal, then process ends</p>
</li>
<li><p>If not, the middle element is either greater or lesser than the item you're searching for. If the middle element is greater, the algorithm splits the list and searches for the element on the left side. If the middle element is smaller, it splits the list and searches for the element on the right side of the list.</p>
</li>
</ul>
<p>You can implement this method using recursion or iteration in the binary search process.</p>
<h3 id="heading-how-the-binary-search-algorithm-works-step-by-step">How the Binary Search Algorithm Works – Step by Step</h3>
<p>First, before performing the search, you need to sort the list.</p>
<p>Then you create a variable that stores the value to be searched for.</p>
<p>Next, the list is divided into two parts. We sum up the first and last indexes to find the index of the middle element in the list.</p>
<p>When the calculated value of the middle element index is a float (like 3.45), we take the whole part as the index.</p>
<p>Then we compare the value we're searching for and the middle element.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/process1--2-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-binary-search-use-case">Binary Search Use Case</h3>
<h4 id="heading-condition-1">Condition 1</h4>
<p>If the middle element is equal to the value to be searched, the position where the value is will be returned and the process is terminated.</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> middle element == to_search 
    <span class="hljs-keyword">return</span> position of middle element 
*code ends*
</code></pre>
<h4 id="heading-using-the-image-above-as-an-example">Using the Image above as an example:</h4>
<p>The middle element = 23, the target value/to_search = 23. Comparing the two values, we see that they are equal on both sides. 23 appears at index 2 in the list. That is the output of the code and the process ends.</p>
<h4 id="heading-condition-2">Condition 2</h4>
<p>If the middle element is not equal to "to_search", then we check the following scenarios:</p>
<p><strong>Scenario 1</strong>: if the middle element is greater than the value to be searched:</p>
<p><code>if middle element &gt; to_search</code></p>
<ul>
<li><p>the search moves to the left side because the values are less than the middle element</p>
</li>
<li><p>the position of the middle element shifts to the left by 1</p>
</li>
<li><p>new_position = index(middle element) - 1</p>
</li>
<li><p>a new search begins and the search ends at that new position and it takes all the values before it.</p>
</li>
</ul>
<h4 id="heading-using-the-image-above-as-an-example-1">Using the image above as an example:</h4>
<pre><code class="lang-python">middle element = <span class="hljs-number">23</span>
to_search = <span class="hljs-number">4</span>
<span class="hljs-keyword">if</span> <span class="hljs-number">23</span> &gt; <span class="hljs-number">4</span>
</code></pre>
<ul>
<li><p>we move to the left side because all numbers less than 23 are stored there. index (23) = 2</p>
</li>
<li><p>new_position = index(23) - 1 = 2-1 = 1</p>
</li>
<li><p>The search will end at index 1 and take all other value(s) before index 1</p>
</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/leftside.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Comparing the new middle element (4) to the target value (4), we see they are equal. So the search is terminated and the output is the position "4" occupies in the list (which is index 0).</p>
<p><strong>Scenario 2</strong>: if the middle element is less than the value to be searched:</p>
<p><code>if middle element &lt; to_search</code></p>
<ul>
<li><p>the search moves to the right side because the values are greater than the middle element</p>
</li>
<li><p>the position of the middle element shifts to the right by 1</p>
</li>
<li><p>new_position = index(middle element) + 1</p>
</li>
<li><p>a new search begins at the new position and ends at the last index in the list</p>
</li>
<li><p>all values are taken from the new position to the end of the list</p>
</li>
</ul>
<h4 id="heading-using-the-first-image-as-an-example">Using the first Image as an example:</h4>
<pre><code class="lang-python">middle element = <span class="hljs-number">23</span> 
to_search = <span class="hljs-number">32</span> 
<span class="hljs-keyword">if</span> <span class="hljs-number">23</span> &gt; <span class="hljs-number">32</span>
</code></pre>
<ul>
<li><p>we move to the right side because all numbers greater than 23 are stored there. index(23) = 2 ,</p>
</li>
<li><p>new_position = index(23) + 1 = 2+1 = 3</p>
</li>
<li><p>The search will begin at index 3 and take all other value(s) after index 3</p>
</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/rightside.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Comparing the middle element (32) to the target value (32), we see they are equal. So the search is terminated and the output is the position "4" occupies in the list (index 4).</p>
<h2 id="heading-methods-used-in-binary-search-algorithms">‌‌Methods Used in Binary Search Algorithms</h2>
<p>There are two methods that can implement the “divide and conquer” technique in the search. They are iteration and recursion.</p>
<h3 id="heading-what-is-iteration">What is Iteration?</h3>
<p>In order to get elements from a tuple, list, or dictionary, you iterate through the items with loops.</p>
<p>Iteration is a repeated sequence of statements during execution and it has a countable number of values. For example, when looping through random lists, we loop through the actual variable containing the lists to get the values.</p>
<h4 id="heading-code-implementation-for-binary-search-with-iteration">Code implementation for binary search with iteration</h4>
<p>Here's the code:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">binary_search</span>(<span class="hljs-params">list_num , to_search</span>):</span>
    first_index = <span class="hljs-number">0</span>
    size = len(list_num)
    last_index = size - <span class="hljs-number">1</span>
    mid_index = (first_index + last_index) // <span class="hljs-number">2</span>
    <span class="hljs-comment"># print(mid_index)</span>
    mid_element = list_num[mid_index]
    <span class="hljs-comment"># print(mid_element)</span>

    is_found = <span class="hljs-literal">True</span>
    <span class="hljs-keyword">while</span> is_found:
        <span class="hljs-keyword">if</span> first_index == last_index:
            <span class="hljs-keyword">if</span> mid_element != to_search:
                is_found = <span class="hljs-literal">False</span>
                <span class="hljs-keyword">return</span> <span class="hljs-string">" Does not appear in the list"</span>

        <span class="hljs-keyword">elif</span> mid_element == to_search:
            <span class="hljs-keyword">return</span> <span class="hljs-string">f"<span class="hljs-subst">{mid_element}</span> occurs in position <span class="hljs-subst">{mid_index}</span>"</span>

        <span class="hljs-keyword">elif</span> mid_element &gt; to_search:
            new_position = mid_index - <span class="hljs-number">1</span>
            last_index = new_position
            mid_index = (first_index + last_index) // <span class="hljs-number">2</span>
            mid_element = list_num[mid_index]
            <span class="hljs-keyword">if</span> mid_element == to_search:
                <span class="hljs-keyword">return</span> <span class="hljs-string">f"<span class="hljs-subst">{mid_element}</span> occurs in position <span class="hljs-subst">{mid_index}</span>"</span>

        <span class="hljs-keyword">elif</span> mid_element &lt; to_search:
            new_position = mid_index + <span class="hljs-number">1</span>
            first_index = new_position
            last_index = size - <span class="hljs-number">1</span>
            mid_index = (first_index + last_index) // <span class="hljs-number">2</span>
            mid_element = list_num[mid_index]
            <span class="hljs-keyword">if</span> mid_element == to_search:
                <span class="hljs-keyword">return</span> <span class="hljs-string">f"<span class="hljs-subst">{mid_element}</span> occurs in position <span class="hljs-subst">{mid_index}</span>"</span>



list_container = [<span class="hljs-number">16</span> , <span class="hljs-number">18</span> , <span class="hljs-number">20</span> , <span class="hljs-number">50</span> , <span class="hljs-number">60</span> , <span class="hljs-number">81</span> , <span class="hljs-number">84</span> , <span class="hljs-number">89</span>]
print(binary_search(list_container , <span class="hljs-number">81</span>))
print(binary_search(list_container , <span class="hljs-number">10</span>))
</code></pre>
<p>Now let's see what's going on here:</p>
<ul>
<li><p>First, we pass in a list and a value to be searched (to_search) as an input to a function.</p>
</li>
<li><p>In the function, we create a variable name of first index and assign it to "0". The first index in a list is always "0".</p>
</li>
<li><p>Then we create four variable names: "size" to store the length of the list, "last_index" to store the index of the last element, "mid_index" to store the operation of finding the middle element index, and "mid_element" to store the middle element gotten from the list using the mid index as position.</p>
</li>
<li><p>Afterwards, we introduce a while loop to make the conditions run on repeat. Above the while loop we create a variable name "is_found" and set it to "True". This condition checks if the "item to be searched" is found or not.</p>
</li>
<li><p>In the while loop, we check all the conditions. The first condition is to check if the middle element and the variable "to_search" are equal. If they are equal, the position of the item will be returned.</p>
</li>
<li><p>Then we check for the second condition (if middle element != item to be searched) which leads us to the two scenarios:<br>  – if the middle element is greater than the item to be searched, the new position will shift to the left once. The search will begin from the first index and end at the new position which is the new last index.<br>  – If the middle element is less than the item to be searched, the new position will shift to the right once. The search will begin from the new position as the new first index and end at the last index.</p>
</li>
</ul>
<p>At the end of these scenarios, we check if the new middle element is the same as the item to be searched. If it is the same, the position of the item will be returned. If not, the conditions are checked until the values are equal.</p>
<p>For error handling, let's say we want to search for a value that does not appear in the list. If we end at the two conditions, the loop will keep running and may eventually crash the system.</p>
<p>To catch the error, we set a condition to check if the first index equals the last index. Then we check if the middle element is equal to the item to be searched. If it is not equal," is found" will be "False". When you run this, it shows an empty array. In my code, the output is a statement.</p>
<p>The final step is to call the function and the result is displayed.</p>
<p><strong>And here are the results:</strong></p>
<p>If the element is in the list, the output is the position.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-194.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If the element is not in the list, the output is a statement like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-195.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-what-is-recursion">What is ‌‌Recursion?</h3>
<p>A function is said to be recursive if it makes reference to itself or previous term(s) to solve a task.</p>
<p>A recursive function is repetitive and it is executed in sequence. It starts from a complex problem and breaks things down into a simpler form.</p>
<h4 id="heading-code-implementation-for-binary-search-with-recursion">Code implementation for binary search with recursion</h4>
<p>With recursion, it is a bit simpler and requires less code. Here's what it looks like:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">binary_search</span>(<span class="hljs-params">list_num, first_index, last_index, to_search</span>):</span>
    <span class="hljs-keyword">if</span> last_index &gt;= first_index:

        mid_index = (first_index + last_index) // <span class="hljs-number">2</span>
        mid_element = list_num[mid_index]


        <span class="hljs-keyword">if</span> mid_element == to_search:
            <span class="hljs-keyword">return</span> <span class="hljs-string">f"<span class="hljs-subst">{mid_element}</span> occurs in position <span class="hljs-subst">{mid_index}</span>"</span>

        <span class="hljs-keyword">elif</span> mid_element &gt; to_search:
            new_position = mid_index - <span class="hljs-number">1</span>
            <span class="hljs-comment"># new last index is the new position</span>
            <span class="hljs-keyword">return</span> binary_search(list_num, first_index, new_position, to_search)

        <span class="hljs-keyword">elif</span> mid_element &lt; to_search:
            new_position = mid_index + <span class="hljs-number">1</span>
             <span class="hljs-comment"># new first index is the new position</span>
            <span class="hljs-keyword">return</span> binary_search(list_num, new_position, last_index, to_search)

    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-string">" Does not appear in the list"</span>

list_container = [ <span class="hljs-number">1</span>, <span class="hljs-number">9</span>, <span class="hljs-number">11</span>, <span class="hljs-number">21</span>, <span class="hljs-number">34</span>, <span class="hljs-number">54</span>, <span class="hljs-number">67</span>, <span class="hljs-number">90</span> ]
search = <span class="hljs-number">34</span>
first = <span class="hljs-number">0</span>
last= len(list_container) - <span class="hljs-number">1</span>

print(binary_search(list_container,first,last,search))
</code></pre>
<ul>
<li><p>First, a function accepts four inputs: the first index, last index, list, and to_search (item to be searched).</p>
</li>
<li><p>Then we check if the value of the last index is greater than or equal to the value of the first index. If the condition is true, we assign the operation of finding the middle element index to the variable name "mid_index". Then the middle element is gotten from the list using the mid index as position.</p>
</li>
<li><p>We create an "if" statement under the first "if" block to check if the middle element and the variable "to_search" are equal. If they are equal, the position of the item will be returned.</p>
</li>
<li><p>Then we check for the second condition, (if middle element != item to be searched) which leads us to two scenarios:<br>  – if the middle element is greater than the item to be searched, the new position will shift to the left once. The search will begin from the first index and end at the new position. We return the function and pass in the new position as the last index value.<br>  – if the middle element is less than the item to be searched, the new position will shift to the right once. The search will begin from the new position and end at the last index. We return the function and pass in the new position as the first index value.</p>
</li>
<li><p>The last condition will be on the same indent as the first "if" statement. If the to_search is not in the list, it will return a statement</p>
</li>
</ul>
<p>The final step is to call the function and the result is displayed.</p>
<p><strong>And here are the results:</strong></p>
<p>If the element is in the list, the output is the position:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-196.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If the element is not in the list, the output is a statement:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-197.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-real-life-examples-of-binary-search">Real-life Examples of Binary Search‌</h2>
<p>You might not realize it, but we perform binary search all the time. Here are a few examples of how you might use or encounter it in your daily life or work:</p>
<ul>
<li><p>Searching for a word in a dictionary</p>
</li>
<li><p>searching for a literature text book in a literature section in a library</p>
</li>
<li><p>searching for an element in a sorted list</p>
</li>
<li><p>searching for students taller than 5 feet 3 inches in a line of students arranged according to their heights.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>At the end of this article, you should be familiar with how binary search algorithms work and how to implement them in code.</p>
<p>It's fine if you could not grasp everything at once – just give yourself some time and practice. If you encounter any errors or have questions, you can reach out to me on <a target="_blank" href="https://twitter.com/HeritageAlabi1">Twitter</a>.</p>
<p>‌‌</p>
<p>‌‌</p>
<p>‌‌</p>
<p>‌‌</p>
<p>‌‌</p>
<p>‌‌</p>
<p>‌</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Binary Search Tree Traversal – Inorder, Preorder, Post Order for BST ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, you will learn what a binary search tree is, what parts make up a tree, and some of the common terms we use when describing parts of a tree.  We will also see how to traverse a tree using some of the common algorithms – all ]]>
                </description>
                <link>https://www.freecodecamp.org/news/binary-search-tree-traversal-inorder-preorder-post-order-for-bst/</link>
                <guid isPermaLink="false">66b0a27bd7edba94d20b3ba8</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Wed, 26 Jan 2022 20:01:40 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/01/binary-search-tree-traversal.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, you will learn what a binary search tree is, what parts make up a tree, and some of the common terms we use when describing parts of a tree. </p>
<p>We will also see how to traverse a tree using some of the common algorithms – all illustrated with clear examples.</p>
<h2 id="heading-what-is-a-binary-search-tree">What Is a Binary Search Tree?</h2>
<p>A binary search tree is a binary tree made up of nodes. Each node has a key signifying its value. </p>
<p>The value of the nodes on the left subtree are smaller than the value of the root node. And the value of the nodes on the right subtree are larger than the value of the root node. </p>
<p>The root node is the parent node of both subtrees.</p>
<p>The diagram below shows the main parts of a binary tree:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/binary-tree.png" alt="Image" width="600" height="400" loading="lazy">
<em>Diagram of a binary search tree</em></p>
<p>Let's us look at the relationship between the nodes. </p>
<ul>
<li><code>**A**</code> is the root node. </li>
<li>The left subtree begins at <strong><code>B</code></strong> while the right subtree begins at <strong><code>C</code></strong>.</li>
<li>Node <strong><code>A</code></strong> has two child nodes – <strong><code>B</code></strong> and <strong><code>C</code></strong>.</li>
<li>Node <strong><code>C</code></strong> is the parent node to <strong><code>F</code></strong> and <strong><code>G</code></strong>. <strong><code>F</code></strong> and <strong><code>G</code></strong> are siblings.</li>
<li>Node <strong><code>F</code></strong> and <strong><code>G</code></strong> are know as <strong>leaf</strong> nodes because they do not have children.</li>
<li>Node <strong><code>B</code></strong> is the parent node to <strong><code>D</code></strong> and <strong><code>E</code></strong>.</li>
<li>Node <strong><code>D</code></strong> is the parent node to <strong><code>H</code></strong> and <strong><code>I</code></strong>.</li>
<li><strong><code>D</code></strong> and <strong><code>E</code></strong> are siblings as well as <strong><code>H</code></strong> and <strong><code>I</code></strong>.</li>
<li>Node <strong><code>E</code></strong>  is a leaf node.</li>
</ul>
<p>So here are some important terms that we just used to describe the tree above:</p>
<p><strong>Root:</strong> The topmost node in the tree.</p>
<p><strong>Parent:</strong> A node with a child or children.</p>
<p><strong>Child:</strong> A node extended from another node (parent node).</p>
<p><strong>Leaf:</strong> A node without a child.</p>
<h2 id="heading-what-is-a-binary-search-tree-used-for">What Is a Binary Search Tree Used For?</h2>
<p>Binary search trees help us speed up our binary search as we are able to find items faster. </p>
<p>We can use the binary search tree for the addition and deletion of items in a tree. </p>
<p>We can also represent data in a ranked order using a binary tree. And in some cases, it can be used as a chart to represent a collection of information.</p>
<p>Next, we'll look at some techniques used in traversing a binary tree.</p>
<h2 id="heading-what-is-tree-traversal">What is Tree Traversal?</h2>
<p>Traversing a tree means visiting and outputting the value of each node in a particular order. In this tutorial, we will use the Inorder, Preorder, and Post order tree traversal methods.</p>
<p>The major importance of tree traversal is that there are multiple ways of carrying out traversal operations unlike linear data structures like arrays, bitmaps, matrices where traversal is done in a linear order.</p>
<p>Each of these methods of traversing a tree have a particular order they follow:</p>
<ul>
<li>For <strong>Inorder</strong>, you traverse from the <strong>left</strong> subtree to the <strong>root</strong> then to the <strong>right</strong> subtree.</li>
<li>For <strong>Preorder</strong>, you traverse from the <strong>root</strong> to the <strong>left</strong> subtree then to the <strong>right</strong> subtree.</li>
<li>For <strong>Post order</strong>, you traverse from the <strong>left</strong> subtree to the <strong>right</strong> subtree then to the <strong>root</strong>.</li>
</ul>
<p>Here is another way of representing the information above:</p>
<p>Inorder =&gt; Left, Root, Right.</p>
<p>Preorder =&gt; Root, Left, Right.</p>
<p>Post order =&gt; Left, Right, Root.</p>
<h3 id="heading-how-to-traverse-a-tree-using-inorder-traversal">How to Traverse a Tree Using Inorder Traversal</h3>
<p>We are going to create a tree similar to the one in the last section, but this time the node keys will be numbers instead of letters. </p>
<p>Remember that the values of the nodes on the left subtree are always smaller than the value of the root node. Also, the values of the nodes on the right subtree are larger than the value of the root node. </p>
<p>Here is the diagram we will be working with:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/ex-binary-search-tree.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Recall that the order for inorder traversal is Left, Root, Right.</p>
<p>This is the result we get after using inorder traversal:</p>
<p><strong>D, B, E, A, F, C, G</strong></p>
<p>If that seems a bit complex for you to understand, then follow the order of the colors in the picture below</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/ex-inorder-traversal.png" alt="Image" width="600" height="400" loading="lazy">
<em>Inorder traversal</em></p>
<h3 id="heading-how-to-traverse-a-tree-using-preorder-traversal">How to Traverse a Tree Using Preorder Traversal</h3>
<p>The order here is Root, Left, Right.</p>
<p>Using the same diagram above, we have:</p>
<p><strong>A, B, D, E, C, F, G</strong></p>
<p>Here is the same diagram with different colors used as a guide:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/ex-preorder-traversal.png" alt="Image" width="600" height="400" loading="lazy">
<em>Preorder traversal</em></p>
<h3 id="heading-how-to-traverse-a-tree-using-postorder-traversal">How to Traverse a Tree Using Postorder Traversal</h3>
<p>The order for post order traversal is Left, Right, Root.</p>
<p>Here is the output:</p>
<p><strong>D, E, B, F, G, C, A</strong></p>
<p>If you can't figure out how we arrived at that result, then use the colors in the picture below as a guide:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/ex-post-order-traversal.png" alt="Image" width="600" height="400" loading="lazy">
<em>Postorder traversal</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, we learned the basics of what a binary search tree is, what the various parts of a binary tree are, and the common terms associated with a tree. We also saw some of the algorithms we can use to traverse a tree.</p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Search Algorithms – Linear Search and Binary Search Code Implementation and Complexity Analysis ]]>
                </title>
                <description>
                    <![CDATA[ Search algorithms are a fundamental computer science concept that you should understand as a developer. They work by using a step-by-step method to locate specific data among a collection of data. In this article, we'll learn how search algorithms wo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/search-algorithms-linear-and-binary-search-explained/</link>
                <guid isPermaLink="false">66ba0ebe9065919bb4e84ca5</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ #big o notation ]]>
                    </category>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Computer Science ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ashutosh Krishna ]]>
                </dc:creator>
                <pubDate>Tue, 11 Jan 2022 17:21:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/01/searching.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><strong>Search algorithms</strong> are a fundamental computer science concept that you should understand as a developer. They work by using a step-by-step method to locate specific data among a collection of data.</p>
<p>In this article, we'll learn how search algorithms work by looking at their implementations in Java and Python.</p>
<h2 id="heading-what-is-a-search-algorithm">What is a Search Algorithm?</h2>
<p>According to Wikipedia, a search algorithm is:</p>
<blockquote>
<p><em>Any algorithm which solves the search problem, namely, to retrieve information stored within some data structure, or calculated in the search space of a problem domain, either with discrete or continuous values.</em></p>
</blockquote>
<p>Search algorithms are designed to check or retrieve an element from any data structure where that element is being stored. They search for a target (key) in the search space.</p>
<h2 id="heading-types-of-search-algorithms">Types of Search Algorithms</h2>
<p>In this post, we are going to discuss two important types of search algorithms:</p>
<ol>
<li><p><strong>Linear or Sequential Search</strong></p>
</li>
<li><p><strong>Binary Search</strong></p>
</li>
</ol>
<p>Let's discuss these two in detail with examples, code implementations, and time complexity analysis.</p>
<h2 id="heading-linear-or-sequential-search">Linear or Sequential Search</h2>
<p>This algorithm works by sequentially iterating through the whole array or list from one end until the target element is found. If the element is found, it returns its index, else -1.</p>
<p>Now let's look at an example and try to understand how it works:</p>
<pre><code class="lang-python">arr = [<span class="hljs-number">2</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">11</span>, <span class="hljs-number">7</span>, <span class="hljs-number">19</span>, <span class="hljs-number">45</span>]
</code></pre>
<p>Suppose the target element we want to search is <code>7</code>.</p>
<h3 id="heading-approach-for-linear-or-sequential-search">Approach for Linear or Sequential Search</h3>
<ul>
<li><p>Start with index 0 and compare each element with the target</p>
</li>
<li><p>If the target is found to be equal to the element, return its index</p>
</li>
<li><p>If the target is not found, return -1</p>
</li>
</ul>
<h3 id="heading-code-implementation"><strong>Code Implementation</strong></h3>
<p>Let's now look at how we'd implement this type of search algorithm in a couple different programming languages.</p>
<h4 id="heading-linear-or-sequential-search-in-java">Linear or Sequential Search in Java</h4>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> algorithms.searching;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LinearSearch</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-keyword">int</span>[] nums = {<span class="hljs-number">2</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">11</span>, <span class="hljs-number">7</span>, <span class="hljs-number">19</span>, <span class="hljs-number">45</span>};
        <span class="hljs-keyword">int</span> target = <span class="hljs-number">7</span>;
        System.out.println(search(nums, target));

    }

    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">search</span><span class="hljs-params">(<span class="hljs-keyword">int</span>[] nums, <span class="hljs-keyword">int</span> target)</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> index = <span class="hljs-number">0</span>; index &lt; nums.length; index++) {
            <span class="hljs-keyword">if</span> (nums[index] == target) {
                <span class="hljs-keyword">return</span> index;
            }
        }
        <span class="hljs-keyword">return</span> -<span class="hljs-number">1</span>;
    }
}
</code></pre>
<h4 id="heading-linear-or-sequential-search-in-python">Linear or Sequential Search in Python</h4>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">search</span>(<span class="hljs-params">nums, target</span>):</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(nums)):
        <span class="hljs-keyword">if</span> nums[i] == target:
            <span class="hljs-keyword">return</span> i
    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    nums = [<span class="hljs-number">2</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">11</span>, <span class="hljs-number">7</span>, <span class="hljs-number">19</span>, <span class="hljs-number">45</span>]
    target = <span class="hljs-number">7</span>
    print(search(nums, target))
</code></pre>
<h3 id="heading-time-complexity-analysis"><strong>Time Complexity Analysis</strong></h3>
<p><strong>The Best Case</strong> occurs when the target element is the first element of the array. The number of comparisons, in this case, is 1. So, the time complexity is <code>O(1)</code>.</p>
<p><strong>The Average Case:</strong> On average, the target element will be somewhere in the middle of the array. The number of comparisons, in this case, will be N/2. So, the time complexity will be <code>O(N)</code> (the constant being ignored).</p>
<p><strong>The Worst Case</strong> occurs when the target element is the last element in the array or not in the array. In this case, we have to traverse the entire array, and so the number of comparisons will be N. So, the time complexity will be <code>O(N)</code>.</p>
<h2 id="heading-binary-search">Binary Search</h2>
<p>This type of searching algorithm is used to find the position of a specific value contained <strong>in a sorted array</strong>. The binary search algorithm works on the principle of divide and conquer and it is considered the best searching algorithm because it's faster to run.</p>
<p>Now let's take a sorted array as an example and try to understand how it works:</p>
<pre><code class="lang-python">arr = [<span class="hljs-number">2</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">17</span>, <span class="hljs-number">27</span>, <span class="hljs-number">29</span>, <span class="hljs-number">45</span>]
</code></pre>
<p>Suppose the target element to be searched is <code>17</code>.</p>
<h3 id="heading-approach-for-binary-search"><strong>Approach for Binary Search</strong></h3>
<ul>
<li><p>Compare the target element with the middle element of the array.</p>
</li>
<li><p>If the target element is greater than the middle element, then the search continues in the right half.</p>
</li>
<li><p>Else if the target element is less than the middle value, the search continues in the left half.</p>
</li>
<li><p>This process is repeated until the middle element is equal to the target element, or the target element is not in the array</p>
</li>
<li><p>If the target element is found, its index is returned, else -1 is returned.</p>
</li>
</ul>
<h3 id="heading-code-implementation-1">Code Implementation</h3>
<h4 id="heading-binary-search-in-java">Binary Search in Java</h4>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> algorithms.searching;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BinarySearch</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-keyword">int</span>[] nums = {<span class="hljs-number">2</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">17</span>, <span class="hljs-number">27</span>, <span class="hljs-number">29</span>, <span class="hljs-number">45</span>};
        <span class="hljs-keyword">int</span> target = <span class="hljs-number">17</span>;
        System.out.println(search(nums, target));
    }

    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">search</span><span class="hljs-params">(<span class="hljs-keyword">int</span>[] nums, <span class="hljs-keyword">int</span> target)</span> </span>{
        <span class="hljs-keyword">int</span> start = <span class="hljs-number">0</span>;
        <span class="hljs-keyword">int</span> end = nums.length - <span class="hljs-number">1</span>;

        <span class="hljs-keyword">while</span> (start &lt;= end) {
            <span class="hljs-keyword">int</span> mid = start + (end - start) / <span class="hljs-number">2</span>;

            <span class="hljs-keyword">if</span> (nums[mid] &gt; target)
                end = mid - <span class="hljs-number">1</span>;
            <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (nums[mid] &lt; target)
                start = mid + <span class="hljs-number">1</span>;
            <span class="hljs-keyword">else</span>
                <span class="hljs-keyword">return</span> mid;
        }
        <span class="hljs-keyword">return</span> -<span class="hljs-number">1</span>;
    }
}
</code></pre>
<h4 id="heading-binary-search-in-python">Binary Search in Python</h4>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">search</span>(<span class="hljs-params">nums, target</span>):</span>
    start = <span class="hljs-number">0</span>
    end = len(nums)<span class="hljs-number">-1</span>

    <span class="hljs-keyword">while</span> start &lt;= end:
        mid = start + (end-start)//<span class="hljs-number">2</span>


        <span class="hljs-keyword">if</span> nums[mid] &gt; target:
            end = mid<span class="hljs-number">-1</span>
        <span class="hljs-keyword">elif</span> nums[mid] &lt; target:
            start = mid+<span class="hljs-number">1</span>
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> mid

    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    nums = [<span class="hljs-number">2</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">17</span>, <span class="hljs-number">27</span>, <span class="hljs-number">29</span>, <span class="hljs-number">45</span>]
    target = <span class="hljs-number">17</span>
    print(search(nums, target))
</code></pre>
<h3 id="heading-time-complexity-analysis-1"><strong>Time Complexity Analysis</strong></h3>
<p><strong>The Best Case</strong> occurs when the target element is the middle element of the array. The number of comparisons, in this case, is 1. So, the time complexity is <code>O(1)</code>.</p>
<p><strong>The Average Case:</strong> On average, the target element will be somewhere in the array. So, the time complexity will be <code>O(logN)</code>.</p>
<p><strong>The Worst Case</strong> occurs when the target element is not in the list or it is away from the middle element. So, the time complexity will be <code>O(logN)</code>.</p>
<h3 id="heading-how-to-calculate-time-complexity">How to Calculate Time Complexity:</h3>
<p>Let's say the iteration in Binary Search terminates after <strong>k</strong> iterations.</p>
<p>At each iteration, the array is divided by half. So let’s say the length of array at any iteration is <strong>N</strong>.</p>
<p>At <strong>Iteration 1,</strong></p>
<pre><code class="lang-markdown">Length of array = N
</code></pre>
<p>At <strong>Iteration 2</strong>,</p>
<pre><code class="lang-markdown">Length of array = N/2
</code></pre>
<p>At <strong>Iteration 3</strong>,</p>
<pre><code class="lang-markdown">Length of array = (N/2)/2 = N/2^2
</code></pre>
<p>At <strong>Iteration k</strong>,</p>
<pre><code class="lang-markdown">Length of array = N/2^k
</code></pre>
<p>Also, we know that after k divisions, the <strong>length of the array becomes 1</strong>: Length of array = <strong>N⁄<sub>2</sub><sup>k</sup> = 1</strong>\=&gt; <strong>N = 2<sup>k</sup></strong></p>
<p>If we apply a log function on both sides: <strong>log<sub>2</sub> (N) = log<sub>2</sub> (2<sup>k</sup>)</strong>\=&gt; <strong>log<sub>2</sub> (N) = k log<sub>2</sub> (2)</strong></p>
<p>As <strong>(log<sub>a</sub> (a) = 1)</strong><br>Therefore,=&gt; <strong>k = log<sub>2</sub> (N)</strong></p>
<p>So now we can see why the time complexity of Binary Search is log<sub>2</sub> (N).</p>
<p>You can also visualize the above two algorithms using the simple tool built by <a target="_blank" href="https://www.linkedin.com/in/dipesh-patil/">Dipesh Patil</a> - <a target="_blank" href="https://dipeshpatil.github.io/algorithms-visualiser/#/searching">Algorithms Visualizer</a>.</p>
<h2 id="heading-order-agnostic-binary-search">Order-agnostic Binary Search</h2>
<p>Suppose, we have to find a target element in a sorted array. We know that the array is sorted, but we don’t know if it’s sorted in ascending or descending order.</p>
<h3 id="heading-approach-for-order-agnostic-binary-search"><strong>Approach for Order-agnostic Binary Search</strong></h3>
<p>The implementation is similar to binary search except that we need to identify whether the array is sorted in ascending order or descending order. This then lets us make the decision about whether to continue the search in the left half of the array or the right half of the array.</p>
<ul>
<li><p>We first compare the target with the middle element</p>
</li>
<li><p>If the array is sorted in ascending order and the target is less than the middle element <strong>OR</strong> the array is sorted in descending order and the target is greater than the middle element, then we continue the search in the lower half of the array by setting <code>end=mid-1</code>.</p>
</li>
<li><p>Otherwise, we perform the search in the upper half of the array by setting <code>start=mid+1</code></p>
</li>
</ul>
<p>The only thing we need to do is to figure out whether the array is sorted in ascending order or descending order. We can easily find this by comparing the first and last elements of the array.</p>
<pre><code class="lang-markdown">if arr[0] <span class="xml"><span class="hljs-tag">&lt; <span class="hljs-attr">arr</span>[<span class="hljs-attr">arr.length-1</span>]
    <span class="hljs-attr">array</span> <span class="hljs-attr">is</span> <span class="hljs-attr">sorted</span> <span class="hljs-attr">in</span> <span class="hljs-attr">ascending</span> <span class="hljs-attr">order</span> 
<span class="hljs-attr">else</span>
    <span class="hljs-attr">array</span> <span class="hljs-attr">is</span> <span class="hljs-attr">sorted</span> <span class="hljs-attr">in</span> <span class="hljs-attr">descending</span> <span class="hljs-attr">order</span></span></span>
</code></pre>
<h3 id="heading-code-implementation-2"><strong>Code Implementation</strong></h3>
<h4 id="heading-order-agnostic-binary-search-in-java">Order-agnostic Binary Search in Java</h4>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> algorithms.searching;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OrderAgnosticBinarySearch</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-keyword">int</span>[] nums1 = {-<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">19</span>, <span class="hljs-number">32</span>, <span class="hljs-number">45</span>, <span class="hljs-number">67</span>, <span class="hljs-number">99</span>};
        <span class="hljs-keyword">int</span>[] nums2 = {<span class="hljs-number">99</span>, <span class="hljs-number">67</span>, <span class="hljs-number">45</span>, <span class="hljs-number">32</span>, <span class="hljs-number">19</span>, <span class="hljs-number">15</span>, <span class="hljs-number">12</span>, <span class="hljs-number">8</span>, <span class="hljs-number">7</span>, <span class="hljs-number">6</span>, <span class="hljs-number">4</span>, <span class="hljs-number">2</span>, -<span class="hljs-number">1</span>};
        <span class="hljs-keyword">int</span> target = -<span class="hljs-number">1</span>;
        System.out.println(search(nums1, target));
        System.out.println(search(nums2, target));
    }

    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">search</span><span class="hljs-params">(<span class="hljs-keyword">int</span>[] arr, <span class="hljs-keyword">int</span> target)</span> </span>{
        <span class="hljs-keyword">int</span> start = <span class="hljs-number">0</span>;
        <span class="hljs-keyword">int</span> end = arr.length - <span class="hljs-number">1</span>;

        <span class="hljs-keyword">boolean</span> isAscending = arr[start] &lt; arr[end];

        <span class="hljs-keyword">while</span> (start &lt;= end) {
            <span class="hljs-keyword">int</span> mid = start + (end - start) / <span class="hljs-number">2</span>;

            <span class="hljs-keyword">if</span> (target == arr[mid])
                <span class="hljs-keyword">return</span> mid;

            <span class="hljs-keyword">if</span> (isAscending) {
                <span class="hljs-keyword">if</span> (target &lt; arr[mid]) {
                    end = mid - <span class="hljs-number">1</span>;
                } <span class="hljs-keyword">else</span> {
                    start = mid + <span class="hljs-number">1</span>;
                }
            } <span class="hljs-keyword">else</span> {
                <span class="hljs-keyword">if</span> (target &lt; arr[mid]) {
                    start = mid + <span class="hljs-number">1</span>;
                } <span class="hljs-keyword">else</span> {
                    end = mid - <span class="hljs-number">1</span>;
                }
            }
        }
        <span class="hljs-keyword">return</span> -<span class="hljs-number">1</span>;
    }


}
</code></pre>
<h4 id="heading-order-agnostic-binary-search-in-python">Order-agnostic Binary Search in Python</h4>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">search</span>(<span class="hljs-params">nums, target</span>):</span>
    start = <span class="hljs-number">0</span>
    end = len(nums)<span class="hljs-number">-1</span>

    is_ascending = nums[start] &lt; nums[end]

    <span class="hljs-keyword">while</span> start &lt;= end:
        mid = start + (end-start)//<span class="hljs-number">2</span>

        <span class="hljs-keyword">if</span> target == nums[mid]:
            <span class="hljs-keyword">return</span> mid

        <span class="hljs-keyword">if</span> is_ascending:
            <span class="hljs-keyword">if</span> target &lt; nums[mid]:
                end = mid<span class="hljs-number">-1</span>
            <span class="hljs-keyword">else</span>:
                start = mid+<span class="hljs-number">1</span>
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">if</span> target &lt; nums[mid]:
                start = mid+<span class="hljs-number">1</span>
            <span class="hljs-keyword">else</span>:
                end = mid<span class="hljs-number">-1</span>

    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    nums1 = [<span class="hljs-number">-1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">19</span>, <span class="hljs-number">32</span>, <span class="hljs-number">45</span>, <span class="hljs-number">67</span>, <span class="hljs-number">99</span>]
    nums2 = [<span class="hljs-number">99</span>, <span class="hljs-number">67</span>, <span class="hljs-number">45</span>, <span class="hljs-number">32</span>, <span class="hljs-number">19</span>, <span class="hljs-number">15</span>, <span class="hljs-number">12</span>, <span class="hljs-number">8</span>, <span class="hljs-number">7</span>, <span class="hljs-number">6</span>, <span class="hljs-number">4</span>, <span class="hljs-number">2</span>, <span class="hljs-number">-1</span>]
    target = <span class="hljs-number">-1</span>
    print(search(nums1, target))
    print(search(nums2, target))
</code></pre>
<h3 id="heading-time-complexity-analysis-2"><strong>Time Complexity Analysis</strong></h3>
<p>There will be no change in the time complexity, so it will be the same as Binary Search.</p>
<h1 id="heading-conclusion"><strong>Conclusion</strong></h1>
<p>In this article, we discussed two of the most important search algorithms along with their code implementations in Python and Java. We also looked at their time complexity analysis.</p>
<p>Thanks for reading!</p>
<p><a target="_blank" href="https://newsletter.ashutoshkrris.tk">Subscribe to my newsletter</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Binary Search Tree Algorithms for JavaScript Beginners ]]>
                </title>
                <description>
                    <![CDATA[ I recently had the chance to teach high school students how to code. There are not that many beginner-friendly tutorials on algorithms coded in JavaScript which is the language they were learning. So I decided to make one. In this article, I will try... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/binary-tree-algorithms-for-javascript-beginners/</link>
                <guid isPermaLink="false">66c3461293db2451bd441414</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 11 Aug 2021 23:50:28 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/07/binarytree.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I recently had the chance to teach high school students how to code. There are not that many beginner-friendly tutorials on algorithms coded in JavaScript which is the language they were learning. So I decided to make one.</p>
<p>In this article, I will try my best to explain some core algorithms you should learn before a coding interview.</p>
<p>If you are not familiar with the concept of a binary tree, I encourage you to check out the <a target="_blank" href="https://en.wikipedia.org/wiki/Binary_tree">wikipedia</a> page. If you fully master those basic algorithms, you will have an easier time solving more complex problems.</p>
<h2 id="heading-what-is-a-binary-search-tree-bst">What is a Binary Search Tree (BST)?</h2>
<p>Commonly found in coding interviews, BST is a tree-like data structure with a single root at the very top. They are a great way to store numeric values as their ordered nature allows for fast search and lookups. </p>
<p>Compared to a normal tree, BST has the following properties:</p>
<ul>
<li>every left child has a smaller value than its parent</li>
<li>every right child has a larger value than its parent</li>
<li>every node can contain from 0 to 2 children.</li>
</ul>
<p>The following diagram should clarify things a bit more. </p>
<h2 id="heading-definition-of-a-binary-tree-node">Definition of a Binary Tree Node</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/Untitled_Artwork-25.png" alt="Image" width="600" height="400" loading="lazy">
<em>A binary search tree</em></p>
<p>We usually define a Binary Tree Node with the following function in Javascript:</p>
<pre><code class="lang-js"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TreeNode</span>(<span class="hljs-params">val, left, right</span>) </span>{
     <span class="hljs-built_in">this</span>.val = val
     <span class="hljs-built_in">this</span>.left = left
     <span class="hljs-built_in">this</span>.right = right
 }
</code></pre>
<h2 id="heading-binary-tree-basic-traversals-inorder-postorder-preorder">Binary Tree Basic Traversals (Inorder, Postorder, Preorder)</h2>
<p>The first thing to know is how to loop through each node of the BST. This allows us to perform a function on all nodes of our BST. For example, if we want to find a value <code>x</code> in our BST, we'd need the nodes. </p>
<p>There are three main ways of doing this. Luckily, they share common themes.</p>
<h3 id="heading-inorder-traversal">Inorder traversal</h3>
<p>A recursive algorithm is the easiest way to get started with binary tree inorder traversal. The idea is as follows:</p>
<ul>
<li>If the node is null, do nothing – else, recursively call the function on the node's left child.</li>
<li>Then, do some operation on the node after traversing though all left children. Our current node is guaranteed to be the leftest node.</li>
<li>Finally, call the function on node.right.</li>
</ul>
<p>The Inorder algorithm traverses the tree nodes from left, to mid, to right. </p>
<pre><code class="lang-js"><span class="hljs-comment">/**
* <span class="hljs-doctag">@param <span class="hljs-type">{TreeNode}</span> <span class="hljs-variable">root</span></span>
*/</span>
<span class="hljs-keyword">const</span> inorder = <span class="hljs-function">(<span class="hljs-params">root</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> nodes = []
    <span class="hljs-keyword">if</span> (root) {
        inorder(root.left)
        nodes.push(root.val)
        inorder(root.right)
    }
    <span class="hljs-keyword">return</span> nodes
}
<span class="hljs-comment">// for our example tree, this returns [1,2,3,4,5,6]</span>
</code></pre>
<h3 id="heading-postorder-traversal">Postorder traversal</h3>
<p>A recursive algorithm is the easiest way to get started with the postorder traversal.</p>
<ul>
<li>If the node is null, do nothing – else, recursively call the function on the node's left child.</li>
<li>When there are no more left children, call the function on node.right.</li>
<li>Finally, do some operation on the node.</li>
</ul>
<p>Postorder traversal visits the tree nodes from left, to right, to mid. </p>
<pre><code class="lang-js"><span class="hljs-comment">/**
* <span class="hljs-doctag">@param <span class="hljs-type">{TreeNode}</span> <span class="hljs-variable">root</span></span>
*/</span>
<span class="hljs-keyword">const</span> postorder = <span class="hljs-function">(<span class="hljs-params">root</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> nodes = []
    <span class="hljs-keyword">if</span> (root) {
        postorder(root.left)
        postorder(root.right)
        nodes.push(root.val)
    }
    <span class="hljs-keyword">return</span> nodes
}
<span class="hljs-comment">// for our example tree, this returns [1,3,2,6,5,4]</span>
</code></pre>
<h3 id="heading-preorder-traversal">Preorder traversal</h3>
<p>A recursive algorithm is the easiest way to get started with the preorder traversal.</p>
<ul>
<li>If the node is null, do nothing – else, do some operation on the node.</li>
<li>Traverse to the left child of the node and repeat.</li>
<li>Traverse to the right child of node and repeat.</li>
</ul>
<p>Postorder traversal visits the tree nodes from mid, to left, to right. </p>
<pre><code class="lang-js"><span class="hljs-comment">/**
* <span class="hljs-doctag">@param <span class="hljs-type">{TreeNode}</span> <span class="hljs-variable">root</span></span>
*/</span>
<span class="hljs-keyword">const</span> preorder = <span class="hljs-function">(<span class="hljs-params">root</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> nodes = []
    <span class="hljs-keyword">if</span> (root) {
        nodes.push(root.val)
        preorder(root.left)
        preorder(root.right)
    }
    <span class="hljs-keyword">return</span> nodes
}
<span class="hljs-comment">// for our example tree, this returns [4,2,1,3,5,6]</span>
</code></pre>
<h2 id="heading-what-is-a-valid-binary-search-tree">What is a Valid Binary Search Tree?</h2>
<p>A valid binary search tree (BST) has ALL left children with values less than the parent node, and ALL right children with values greater than the parent node.</p>
<p>To verify if a tree is a valid binary search tree:</p>
<ul>
<li>Define the min and max value the current node can have</li>
<li>If a node's value is not within those bounds, return false</li>
<li>Recursively validate the node's left children, with the max bound set to the node's value</li>
<li>Recursively validate the node's right children, with the min bound set to the node's value</li>
</ul>
<pre><code class="lang-js"><span class="hljs-comment">/**
* <span class="hljs-doctag">@param <span class="hljs-type">{TreeNode}</span> <span class="hljs-variable">root</span></span>
*/</span>
<span class="hljs-keyword">const</span> isValidBST = <span class="hljs-function">(<span class="hljs-params">root</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> helper = <span class="hljs-function">(<span class="hljs-params">node, min, max</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (!node) <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
        <span class="hljs-keyword">if</span> (node.val &lt;= min || node.val &gt;= max) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
        <span class="hljs-keyword">return</span> helper(node.left, min, node.val) &amp;&amp; helper(node.right, node.val, max)
    }
    <span class="hljs-keyword">return</span> helper(root, <span class="hljs-built_in">Number</span>.MIN_SAFE_INTEGER, <span class="hljs-built_in">Number</span>.MAX_SAFE_INTEGER)
}
</code></pre>
<h2 id="heading-how-to-find-binary-tree-max-depth">How to Find Binary Tree Max Depth</h2>
<p>Here, the algorithm is attempting to find the height/depth of our BST. In other words, we are looking at how many 'levels' a BST contains.</p>
<ul>
<li>If the node is null, we return 0 as it does not add any depth</li>
<li>Else we add + 1 to our current depth (we traversed one level)</li>
<li>Recursively calculate the depth of node's children and return the maximum sum between node.left and node.right</li>
</ul>
<pre><code class="lang-js"><span class="hljs-comment">/**
* <span class="hljs-doctag">@param <span class="hljs-type">{TreeNode}</span> <span class="hljs-variable">root</span></span>
*/</span>
<span class="hljs-keyword">const</span> maxDepth = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">root</span>) </span>{
    <span class="hljs-keyword">const</span> calc = <span class="hljs-function">(<span class="hljs-params">node</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (!node) <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.max(<span class="hljs-number">1</span> + calc(node.left), <span class="hljs-number">1</span> + calc(node.right))
    }
    <span class="hljs-keyword">return</span> calc(root)
};
</code></pre>
<h2 id="heading-how-to-find-the-lowest-common-ancestor-between-two-tree-nodes">How to Find the Lowest Common Ancestor Between Two Tree Nodes</h2>
<p>Let's bump up the difficulty. How do we find the common ancestor between two tree nodes in our binary tree? Let's look at some examples.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/Untitled_Artwork-25.png" alt="Image" width="600" height="400" loading="lazy">
<em>A binary search tree</em></p>
<p>In this tree, the lowest common ancestor of 3 and 1 is 2. The LCA of 3 and 2 is 2. The LCA of 6 and 1 and 6 is 4. </p>
<p>See the pattern here? The LCA between two tree nodes is either one of the nodes itself (the case of 3 and 2), or a parent node where the first child is found somewhere in its left subtree, and the second child somewhere in its right subtree.</p>
<p>The algorithm to find the lowest common ancestor (LCA) between two tree nodes p and q is as follows:</p>
<ul>
<li>Verify if p or q is found in the left subtree or right subtree</li>
<li>Then, verify if the current node is p or q</li>
<li>If one of p or q is found in the left or right subtree, and one of p or q is the node itself, we have found the LCA</li>
<li>If both p and q are found in the the left or right subtree, we have found the LCA</li>
</ul>
<pre><code class="lang-js"><span class="hljs-comment">/**
* <span class="hljs-doctag">@param <span class="hljs-type">{TreeNode}</span> <span class="hljs-variable">root</span></span>
* <span class="hljs-doctag">@param <span class="hljs-type">{TreeNode}</span> <span class="hljs-variable">p</span></span>
* <span class="hljs-doctag">@param <span class="hljs-type">{TreeNode}</span> <span class="hljs-variable">q</span></span>
*/</span>
<span class="hljs-keyword">const</span> lowestCommonAncestor = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">root, p, q</span>) </span>{
    <span class="hljs-keyword">let</span> lca = <span class="hljs-literal">null</span>
    <span class="hljs-keyword">const</span> isCommonPath = <span class="hljs-function">(<span class="hljs-params">node</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (!node) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
        <span class="hljs-keyword">var</span> isLeft = isCommonPath(node.left)
        <span class="hljs-keyword">var</span> isRight = isCommonPath(node.right)
        <span class="hljs-keyword">var</span> isMid = node == p || node == q
        <span class="hljs-keyword">if</span> (isMid &amp;&amp; isLeft || isMid &amp;&amp; isRight || isLeft &amp;&amp; isRight) {
            lca = node
        }
        <span class="hljs-keyword">return</span> isLeft || isRight || isMid
    }
    isCommonPath(root)
    <span class="hljs-keyword">return</span> lca
};
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In summary, we have learned how to traverse, verify, and calculate the depth of a BST. </p>
<p>These algorithms are often asked about in coding interviews. It is important to understand them before practicing more advanced BST applications, like finding the LCA of two nodes.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Linear Search Explained ]]>
                </title>
                <description>
                    <![CDATA[ What is Linear Search? Suppose you are given a list or an array of items. You are searching for a particular item. How do you do that? Find the number 13 in the given list. You just look at the list and there it is! Now, how do you tell ]]>
                </description>
                <link>https://www.freecodecamp.org/news/linear-search/</link>
                <guid isPermaLink="false">66c35a8ef83dfae169b2c01e</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 27 Jan 2020 21:58:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9d65740569d1a4ca3786.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-what-is-linear-search"><strong>What is Linear Search?</strong></h2>
<p>Suppose you are given a list or an array of items. You are searching for a particular item. How do you do that?</p>
<p>Find the number 13 in the given list.</p>
<p><img src="https://i.imgur.com/ThkzYEV.jpg" alt="Linear Search 1" width="388" height="71" loading="lazy"></p>
<p>You just look at the list and there it is!</p>
<p><img src="https://i.imgur.com/K7HfCly.jpg" alt="Linear Search 2" width="383" height="74" loading="lazy"></p>
<p>Now, how do you tell a computer to find it?</p>
<p>A computer cannot look at more than the value at a given instant of time. So it takes one item from the array and checks if it is the same as what you are looking for.</p>
<p><img src="https://i.imgur.com/ZOSxeZD.jpg" alt="Linear Search 3" width="184" height="71" loading="lazy"></p>
<p>The first item did not match. So move onto the next one.</p>
<p><img src="https://i.imgur.com/SwKsPxD.jpg" alt="Linear Search 4" width="178" height="68" loading="lazy"></p>
<p>And so on…</p>
<p>This is done till a match is found or until all the items have been checked.</p>
<p><img src="https://i.imgur.com/3AaViff.jpg" alt="Linear Search 5" width="182" height="70" loading="lazy"></p>
<p>In this algorithm, you can stop when the item is found and then there is no need to look further.</p>
<p>So how long would it take to do the linear search operation? In the best case, you could get lucky and the item you are looking at maybe at the first position in the array! </p>
<p>But in the worst case, you would have to look at each and every item before you find the item at the last place or before you realize that the item is not in the array.</p>
<p>The complexity of linear search is therefore O(n).</p>
<p>If the element to be searched lived on the the first memory block then the complexity would be: O(1).</p>
<p>The code for a linear search function in JavaScript is shown below. This function returns the position of the item we are looking for in the array. If the item is not present in the array, the function will return null.</p>
<h3 id="heading-example-in-javascript"><strong>Example in Javascript</strong></h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">linearSearch</span>(<span class="hljs-params">arr, item</span>) </span>{
  <span class="hljs-comment">// Go through all the elements of arr to look for item.</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; arr.length; i++) {
    <span class="hljs-keyword">if</span> (arr[i] === item) { <span class="hljs-comment">// Found it!</span>
      <span class="hljs-keyword">return</span> i;
    }
  }

  <span class="hljs-comment">// Item not found in the array.</span>
  <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
}
</code></pre>
<h3 id="heading-example-in-ruby"><strong>Example in Ruby</strong></h3>
<pre><code class="lang-ruby"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">linear_search</span><span class="hljs-params">(target, array)</span></span>
  counter = <span class="hljs-number">0</span>

  <span class="hljs-keyword">while</span> counter &lt; array.length
    <span class="hljs-keyword">if</span> array[counter] == target
      <span class="hljs-keyword">return</span> counter
    <span class="hljs-keyword">else</span>
      counter += <span class="hljs-number">1</span>
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>
<span class="hljs-keyword">end</span>
</code></pre>
<h3 id="heading-example-in-c"><strong>Example in C++</strong></h3>
<pre><code class="lang-c++"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">linear_search</span><span class="hljs-params">(<span class="hljs-keyword">int</span> arr[],<span class="hljs-keyword">int</span> n,<span class="hljs-keyword">int</span> num)</span>
</span>{
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i=<span class="hljs-number">0</span>;i&lt;n;i++){
        <span class="hljs-keyword">if</span>(arr[i]==num)
            <span class="hljs-keyword">return</span> i;
   }
   <span class="hljs-comment">// Item not found in the array</span>
   <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>; 
}
</code></pre>
<h3 id="heading-example-in-python"><strong>Example in Python</strong></h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">linear_search</span>(<span class="hljs-params">array, num</span>):</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(array)):
        <span class="hljs-keyword">if</span> (array[i]==num):
            <span class="hljs-keyword">return</span> i
    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>
</code></pre>
<h2 id="heading-global-linear-search"><strong>Global Linear Search</strong></h2>
<p>What if you are searching the multiple occurrences of an element? For example you want to see how many 5’s are in an array.</p>
<p>Target = 5</p>
<p>Array = [ 1, 2, 3, 4, 5, 6, 5, 7, 8, 9, 5]</p>
<p>This array has 3 occurrences of 5s and we want to return the indexes (where they are in the array) of all of them. </p>
<p>This is called global linear search and you will need to adjust your code to return an array of the index points at which it finds your target element. </p>
<p>When you find an index element that matches your target, the index point (counter) will be added in the results array. If it doesn’t match, the code will continue to move on to the next element in the array by adding 1 to the counter.</p>
<pre><code class="lang-ruby"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">global_linear_search</span><span class="hljs-params">(target, array)</span></span>
  counter = <span class="hljs-number">0</span>
  results = []

  <span class="hljs-keyword">while</span> counter &lt; array.length
    <span class="hljs-keyword">if</span> array[counter] == target
      results &lt;&lt; counter
      counter += <span class="hljs-number">1</span>
    <span class="hljs-keyword">else</span>
      counter += <span class="hljs-number">1</span>
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>

  <span class="hljs-keyword">if</span> results.empty?
    <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>
  <span class="hljs-keyword">else</span>
    <span class="hljs-keyword">return</span> results
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<h2 id="heading-why-linear-search-is-not-efficient"><strong>Why linear search is not efficient</strong></h2>
<p>There is no doubt that linear search is simple. But because it compares each element one by one, it is time consuming and therefore not very efficient. If we have to find a number from, say, 1,000,000 numbers and that number is at the last position, a linear search technique would become quite tedious. </p>
<p>So you should also learn about bubble sort, quick sort and other more efficient algorithms.</p>
<h2 id="heading-other-search-algorithms">Other search algorithms:</h2>
<ul>
<li><a target="_blank" href="https://guide.freecodecamp.org/certifications/coding-interview-prep/algorithms/implement-quick-sort/">How to implement quick sort</a></li>
<li><a target="_blank" href="https://guide.freecodecamp.org/algorithms/search-algorithms/binary-search/">Binary search algorithm</a></li>
<li><a target="_blank" href="https://guide.freecodecamp.org/algorithms/search-algorithms/jump-search/">Jump search algorithm</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/search-algorithms-explained-with-examples-in-java-python-and-c/">Search algorithms explained with examples</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-implement-a-binary-search-algorithm-in-java-without-recursion-67d9337fd75f/">Implement a binary search algorithm in Java without recursion</a></li>
<li><a target="_blank" href="https://guide.freecodecamp.org/algorithms/search-algorithms">More info on search algorithms</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ AVL Tree Insertion and Rotation ]]>
                </title>
                <description>
                    <![CDATA[ An AVL tree is an improved version of the binary search tree (BST) that is self-balancing. It was named after its inventors Adelson-Velsky and Landis, and was first introduced in 1962, just two years after the design of the binary search tree in 1960... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/avl-tree/</link>
                <guid isPermaLink="false">66c345295ced6d98e4bd3295</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data structures ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Trees ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 15 Jan 2020 22:10:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9dda740569d1a4ca39fa.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>An AVL tree is an improved version of the binary search tree (BST) that is self-balancing. It was named after its inventors <strong>A</strong>delson-<strong>V</strong>elsky and <strong>L</strong>andis, and was first introduced in 1962, just two years after the design of the binary search tree in 1960. The AVL tree is considered to be the first data structure of its type.</p>
<p>A BST is a data structure composed of nodes. It has the following guarantees:</p>
<ol>
<li>Each tree has a root node (at the top).</li>
<li>The root node has zero or more child nodes.</li>
<li>Each child node has zero or more child nodes, and so on.</li>
<li>Each node has up to two children.</li>
<li>For each node, its left descendants are less than the current node, which is less than the right descendants.</li>
</ol>
<p>AVL trees have an additional guarantee:</p>
<ol>
<li>The difference between the depth of right and left subtrees cannot be more than one. </li>
</ol>
<p>In order to maintain this guarantee, implementations of AVL trees include an algorithm to rebalance the tree when adding an additional element would cause the difference in depth between the right and left trees to be greater than one.</p>
<p>AVL trees have a worst case lookup, insert and delete time of O(log n).</p>
<h3 id="heading-right-rotation"><strong>Right Rotation</strong></h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/02/avl_right_rotation.jpg" alt="Image" width="600" height="400" loading="lazy">
_Source: <a target="_blank" href="https://github.com/HebleV/valet_parking/tree/master/images">https://github.com/HebleV/valet_parking/tree/master/images</a>_</p>
<h3 id="heading-left-rotation"><strong>Left Rotation</strong></h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/02/avl_left_rotation.jpg" alt="Image" width="600" height="400" loading="lazy">
_Source: <a target="_blank" href="https://github.com/HebleV/valet_parking/tree/master/images">https://github.com/HebleV/valet_parking/tree/master/images</a>_</p>
<h3 id="heading-avl-insertion-process"><strong>AVL Insertion Process</strong></h3>
<p>This works similarly to a normal binary search tree insertion. After the insertion, you fix the AVL property by using left or right rotations.</p>
<ul>
<li>If there is an imbalance in left child of right subtree, then you perform a left-right rotation.</li>
<li>If there is an imbalance in left child of left subtree, then you perform a right rotation.</li>
<li>If there is an imbalance in right child of right subtree, then you perform a left rotation.</li>
<li>If there is an imbalance in right child of left subtree, then you perform a right-left rotation.</li>
</ul>
<h3 id="heading-example">Example</h3>
<p>Here's an example of an AVL tree in Python:</p>
<pre><code class="lang-py"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">node</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self,value=None</span>):</span>
        self.value=value
        self.left_child=<span class="hljs-literal">None</span>
        self.right_child=<span class="hljs-literal">None</span>
        self.parent=<span class="hljs-literal">None</span> <span class="hljs-comment"># pointer to parent node in tree</span>
        self.height=<span class="hljs-number">1</span> <span class="hljs-comment"># height of node in tree (max dist. to leaf) NEW FOR AVL</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AVLTree</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        self.root=<span class="hljs-literal">None</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__repr__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">if</span> self.root==<span class="hljs-literal">None</span>: <span class="hljs-keyword">return</span> <span class="hljs-string">''</span>
        content=<span class="hljs-string">'\n'</span> <span class="hljs-comment"># to hold final string</span>
        cur_nodes=[self.root] <span class="hljs-comment"># all nodes at current level</span>
        cur_height=self.root.height <span class="hljs-comment"># height of nodes at current level</span>
        sep=<span class="hljs-string">' '</span>*(<span class="hljs-number">2</span>**(cur_height<span class="hljs-number">-1</span>)) <span class="hljs-comment"># variable sized separator between elements</span>
        <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
            cur_height+=<span class="hljs-number">-1</span> <span class="hljs-comment"># decrement current height</span>
            <span class="hljs-keyword">if</span> len(cur_nodes)==<span class="hljs-number">0</span>: <span class="hljs-keyword">break</span>
            cur_row=<span class="hljs-string">' '</span>
            next_row=<span class="hljs-string">''</span>
            next_nodes=[]

            <span class="hljs-keyword">if</span> all(n <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span> <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> cur_nodes):
                <span class="hljs-keyword">break</span>

            <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> cur_nodes:

                <span class="hljs-keyword">if</span> n==<span class="hljs-literal">None</span>:
                    cur_row+=<span class="hljs-string">'   '</span>+sep
                    next_row+=<span class="hljs-string">'   '</span>+sep
                    next_nodes.extend([<span class="hljs-literal">None</span>,<span class="hljs-literal">None</span>])
                    <span class="hljs-keyword">continue</span>

                <span class="hljs-keyword">if</span> n.value!=<span class="hljs-literal">None</span>:       
                    buf=<span class="hljs-string">' '</span>*int((<span class="hljs-number">5</span>-len(str(n.value)))/<span class="hljs-number">2</span>)
                    cur_row+=<span class="hljs-string">'%s%s%s'</span>%(buf,str(n.value),buf)+sep
                <span class="hljs-keyword">else</span>:
                    cur_row+=<span class="hljs-string">' '</span>*<span class="hljs-number">5</span>+sep

                <span class="hljs-keyword">if</span> n.left_child!=<span class="hljs-literal">None</span>:  
                    next_nodes.append(n.left_child)
                    next_row+=<span class="hljs-string">' /'</span>+sep
                <span class="hljs-keyword">else</span>:
                    next_row+=<span class="hljs-string">'  '</span>+sep
                    next_nodes.append(<span class="hljs-literal">None</span>)

                <span class="hljs-keyword">if</span> n.right_child!=<span class="hljs-literal">None</span>: 
                    next_nodes.append(n.right_child)
                    next_row+=<span class="hljs-string">'\ '</span>+sep
                <span class="hljs-keyword">else</span>:
                    next_row+=<span class="hljs-string">'  '</span>+sep
                    next_nodes.append(<span class="hljs-literal">None</span>)

            content+=(cur_height*<span class="hljs-string">'   '</span>+cur_row+<span class="hljs-string">'\n'</span>+cur_height*<span class="hljs-string">'   '</span>+next_row+<span class="hljs-string">'\n'</span>)
            cur_nodes=next_nodes
            sep=<span class="hljs-string">' '</span>*int(len(sep)/<span class="hljs-number">2</span>) <span class="hljs-comment"># cut separator size in half</span>
        <span class="hljs-keyword">return</span> content

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">insert</span>(<span class="hljs-params">self,value</span>):</span>
        <span class="hljs-keyword">if</span> self.root==<span class="hljs-literal">None</span>:
            self.root=node(value)
        <span class="hljs-keyword">else</span>:
            self._insert(value,self.root)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_insert</span>(<span class="hljs-params">self,value,cur_node</span>):</span>
        <span class="hljs-keyword">if</span> value&lt;cur_node.value:
            <span class="hljs-keyword">if</span> cur_node.left_child==<span class="hljs-literal">None</span>:
                cur_node.left_child=node(value)
                cur_node.left_child.parent=cur_node <span class="hljs-comment"># set parent</span>
                self._inspect_insertion(cur_node.left_child)
            <span class="hljs-keyword">else</span>:
                self._insert(value,cur_node.left_child)
        <span class="hljs-keyword">elif</span> value&gt;cur_node.value:
            <span class="hljs-keyword">if</span> cur_node.right_child==<span class="hljs-literal">None</span>:
                cur_node.right_child=node(value)
                cur_node.right_child.parent=cur_node <span class="hljs-comment"># set parent</span>
                self._inspect_insertion(cur_node.right_child)
            <span class="hljs-keyword">else</span>:
                self._insert(value,cur_node.right_child)
        <span class="hljs-keyword">else</span>:
            print(<span class="hljs-string">"Value already in tree!"</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_tree</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">if</span> self.root!=<span class="hljs-literal">None</span>:
            self._print_tree(self.root)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_print_tree</span>(<span class="hljs-params">self,cur_node</span>):</span>
        <span class="hljs-keyword">if</span> cur_node!=<span class="hljs-literal">None</span>:
            self._print_tree(cur_node.left_child)
            <span class="hljs-keyword">print</span> (<span class="hljs-string">'%s, h=%d'</span>%(str(cur_node.value),cur_node.height))
            self._print_tree(cur_node.right_child)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">height</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">if</span> self.root!=<span class="hljs-literal">None</span>:
            <span class="hljs-keyword">return</span> self._height(self.root,<span class="hljs-number">0</span>)
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_height</span>(<span class="hljs-params">self,cur_node,cur_height</span>):</span>
        <span class="hljs-keyword">if</span> cur_node==<span class="hljs-literal">None</span>: <span class="hljs-keyword">return</span> cur_height
        left_height=self._height(cur_node.left_child,cur_height+<span class="hljs-number">1</span>)
        right_height=self._height(cur_node.right_child,cur_height+<span class="hljs-number">1</span>)
        <span class="hljs-keyword">return</span> max(left_height,right_height)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">find</span>(<span class="hljs-params">self,value</span>):</span>
        <span class="hljs-keyword">if</span> self.root!=<span class="hljs-literal">None</span>:
            <span class="hljs-keyword">return</span> self._find(value,self.root)
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_find</span>(<span class="hljs-params">self,value,cur_node</span>):</span>
        <span class="hljs-keyword">if</span> value==cur_node.value:
            <span class="hljs-keyword">return</span> cur_node
        <span class="hljs-keyword">elif</span> value&lt;cur_node.value <span class="hljs-keyword">and</span> cur_node.left_child!=<span class="hljs-literal">None</span>:
            <span class="hljs-keyword">return</span> self._find(value,cur_node.left_child)
        <span class="hljs-keyword">elif</span> value&gt;cur_node.value <span class="hljs-keyword">and</span> cur_node.right_child!=<span class="hljs-literal">None</span>:
            <span class="hljs-keyword">return</span> self._find(value,cur_node.right_child)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">delete_value</span>(<span class="hljs-params">self,value</span>):</span>
        <span class="hljs-keyword">return</span> self.delete_node(self.find(value))

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">delete_node</span>(<span class="hljs-params">self,node</span>):</span>

        <span class="hljs-comment">## -----</span>
        <span class="hljs-comment"># Improvements since prior lesson</span>

        <span class="hljs-comment"># Protect against deleting a node not found in the tree</span>
        <span class="hljs-keyword">if</span> node==<span class="hljs-literal">None</span> <span class="hljs-keyword">or</span> self.find(node.value)==<span class="hljs-literal">None</span>:
            print(<span class="hljs-string">"Node to be deleted not found in the tree!"</span>)
            <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span> 
        <span class="hljs-comment">## -----</span>

        <span class="hljs-comment"># returns the node with min value in tree rooted at input node</span>
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">min_value_node</span>(<span class="hljs-params">n</span>):</span>
            current=n
            <span class="hljs-keyword">while</span> current.left_child!=<span class="hljs-literal">None</span>:
                current=current.left_child
            <span class="hljs-keyword">return</span> current

        <span class="hljs-comment"># returns the number of children for the specified node</span>
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">num_children</span>(<span class="hljs-params">n</span>):</span>
            num_children=<span class="hljs-number">0</span>
            <span class="hljs-keyword">if</span> n.left_child!=<span class="hljs-literal">None</span>: num_children+=<span class="hljs-number">1</span>
            <span class="hljs-keyword">if</span> n.right_child!=<span class="hljs-literal">None</span>: num_children+=<span class="hljs-number">1</span>
            <span class="hljs-keyword">return</span> num_children

        <span class="hljs-comment"># get the parent of the node to be deleted</span>
        node_parent=node.parent

        <span class="hljs-comment"># get the number of children of the node to be deleted</span>
        node_children=num_children(node)

        <span class="hljs-comment"># break operation into different cases based on the</span>
        <span class="hljs-comment"># structure of the tree &amp; node to be deleted</span>

        <span class="hljs-comment"># CASE 1 (node has no children)</span>
        <span class="hljs-keyword">if</span> node_children==<span class="hljs-number">0</span>:

            <span class="hljs-keyword">if</span> node_parent!=<span class="hljs-literal">None</span>:
                <span class="hljs-comment"># remove reference to the node from the parent</span>
                <span class="hljs-keyword">if</span> node_parent.left_child==node:
                    node_parent.left_child=<span class="hljs-literal">None</span>
                <span class="hljs-keyword">else</span>:
                    node_parent.right_child=<span class="hljs-literal">None</span>
            <span class="hljs-keyword">else</span>:
                self.root=<span class="hljs-literal">None</span>

        <span class="hljs-comment"># CASE 2 (node has a single child)</span>
        <span class="hljs-keyword">if</span> node_children==<span class="hljs-number">1</span>:

            <span class="hljs-comment"># get the single child node</span>
            <span class="hljs-keyword">if</span> node.left_child!=<span class="hljs-literal">None</span>:
                child=node.left_child
            <span class="hljs-keyword">else</span>:
                child=node.right_child

            <span class="hljs-keyword">if</span> node_parent!=<span class="hljs-literal">None</span>:
                <span class="hljs-comment"># replace the node to be deleted with its child</span>
                <span class="hljs-keyword">if</span> node_parent.left_child==node:
                    node_parent.left_child=child
                <span class="hljs-keyword">else</span>:
                    node_parent.right_child=child
            <span class="hljs-keyword">else</span>:
                self.root=child

            <span class="hljs-comment"># correct the parent pointer in node</span>
            child.parent=node_parent

        <span class="hljs-comment"># CASE 3 (node has two children)</span>
        <span class="hljs-keyword">if</span> node_children==<span class="hljs-number">2</span>:

            <span class="hljs-comment"># get the inorder successor of the deleted node</span>
            successor=min_value_node(node.right_child)

            <span class="hljs-comment"># copy the inorder successor's value to the node formerly</span>
            <span class="hljs-comment"># holding the value we wished to delete</span>
            node.value=successor.value

            <span class="hljs-comment"># delete the inorder successor now that it's value was</span>
            <span class="hljs-comment"># copied into the other node</span>
            self.delete_node(successor)

            <span class="hljs-comment"># exit function so we don't call the _inspect_deletion twice</span>
            <span class="hljs-keyword">return</span>

        <span class="hljs-keyword">if</span> node_parent!=<span class="hljs-literal">None</span>:
            <span class="hljs-comment"># fix the height of the parent of current node</span>
            node_parent.height=<span class="hljs-number">1</span>+max(self.get_height(node_parent.left_child),self.get_height(node_parent.right_child))

            <span class="hljs-comment"># begin to traverse back up the tree checking if there are</span>
            <span class="hljs-comment"># any sections which now invalidate the AVL balance rules</span>
            self._inspect_deletion(node_parent)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">search</span>(<span class="hljs-params">self,value</span>):</span>
        <span class="hljs-keyword">if</span> self.root!=<span class="hljs-literal">None</span>:
            <span class="hljs-keyword">return</span> self._search(value,self.root)
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_search</span>(<span class="hljs-params">self,value,cur_node</span>):</span>
        <span class="hljs-keyword">if</span> value==cur_node.value:
            <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
        <span class="hljs-keyword">elif</span> value&lt;cur_node.value <span class="hljs-keyword">and</span> cur_node.left_child!=<span class="hljs-literal">None</span>:
            <span class="hljs-keyword">return</span> self._search(value,cur_node.left_child)
        <span class="hljs-keyword">elif</span> value&gt;cur_node.value <span class="hljs-keyword">and</span> cur_node.right_child!=<span class="hljs-literal">None</span>:
            <span class="hljs-keyword">return</span> self._search(value,cur_node.right_child)
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span> 


    <span class="hljs-comment"># Functions added for AVL...</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_inspect_insertion</span>(<span class="hljs-params">self,cur_node,path=[]</span>):</span>
        <span class="hljs-keyword">if</span> cur_node.parent==<span class="hljs-literal">None</span>: <span class="hljs-keyword">return</span>
        path=[cur_node]+path

        left_height =self.get_height(cur_node.parent.left_child)
        right_height=self.get_height(cur_node.parent.right_child)

        <span class="hljs-keyword">if</span> abs(left_height-right_height)&gt;<span class="hljs-number">1</span>:
            path=[cur_node.parent]+path
            self._rebalance_node(path[<span class="hljs-number">0</span>],path[<span class="hljs-number">1</span>],path[<span class="hljs-number">2</span>])
            <span class="hljs-keyword">return</span>

        new_height=<span class="hljs-number">1</span>+cur_node.height 
        <span class="hljs-keyword">if</span> new_height&gt;cur_node.parent.height:
            cur_node.parent.height=new_height

        self._inspect_insertion(cur_node.parent,path)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_inspect_deletion</span>(<span class="hljs-params">self,cur_node</span>):</span>
        <span class="hljs-keyword">if</span> cur_node==<span class="hljs-literal">None</span>: <span class="hljs-keyword">return</span>

        left_height =self.get_height(cur_node.left_child)
        right_height=self.get_height(cur_node.right_child)

        <span class="hljs-keyword">if</span> abs(left_height-right_height)&gt;<span class="hljs-number">1</span>:
            y=self.taller_child(cur_node)
            x=self.taller_child(y)
            self._rebalance_node(cur_node,y,x)

        self._inspect_deletion(cur_node.parent)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_rebalance_node</span>(<span class="hljs-params">self,z,y,x</span>):</span>
        <span class="hljs-keyword">if</span> y==z.left_child <span class="hljs-keyword">and</span> x==y.left_child:
            self._right_rotate(z)
        <span class="hljs-keyword">elif</span> y==z.left_child <span class="hljs-keyword">and</span> x==y.right_child:
            self._left_rotate(y)
            self._right_rotate(z)
        <span class="hljs-keyword">elif</span> y==z.right_child <span class="hljs-keyword">and</span> x==y.right_child:
            self._left_rotate(z)
        <span class="hljs-keyword">elif</span> y==z.right_child <span class="hljs-keyword">and</span> x==y.left_child:
            self._right_rotate(y)
            self._left_rotate(z)
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">'_rebalance_node: z,y,x node configuration not recognized!'</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_right_rotate</span>(<span class="hljs-params">self,z</span>):</span>
        sub_root=z.parent 
        y=z.left_child
        t3=y.right_child
        y.right_child=z
        z.parent=y
        z.left_child=t3
        <span class="hljs-keyword">if</span> t3!=<span class="hljs-literal">None</span>: t3.parent=z
        y.parent=sub_root
        <span class="hljs-keyword">if</span> y.parent==<span class="hljs-literal">None</span>:
                self.root=y
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">if</span> y.parent.left_child==z:
                y.parent.left_child=y
            <span class="hljs-keyword">else</span>:
                y.parent.right_child=y        
        z.height=<span class="hljs-number">1</span>+max(self.get_height(z.left_child),
            self.get_height(z.right_child))
        y.height=<span class="hljs-number">1</span>+max(self.get_height(y.left_child),
            self.get_height(y.right_child))

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_left_rotate</span>(<span class="hljs-params">self,z</span>):</span>
        sub_root=z.parent 
        y=z.right_child
        t2=y.left_child
        y.left_child=z
        z.parent=y
        z.right_child=t2
        <span class="hljs-keyword">if</span> t2!=<span class="hljs-literal">None</span>: t2.parent=z
        y.parent=sub_root
        <span class="hljs-keyword">if</span> y.parent==<span class="hljs-literal">None</span>: 
            self.root=y
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">if</span> y.parent.left_child==z:
                y.parent.left_child=y
            <span class="hljs-keyword">else</span>:
                y.parent.right_child=y
        z.height=<span class="hljs-number">1</span>+max(self.get_height(z.left_child),
            self.get_height(z.right_child))
        y.height=<span class="hljs-number">1</span>+max(self.get_height(y.left_child),
            self.get_height(y.right_child))

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_height</span>(<span class="hljs-params">self,cur_node</span>):</span>
        <span class="hljs-keyword">if</span> cur_node==<span class="hljs-literal">None</span>: <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
        <span class="hljs-keyword">return</span> cur_node.height

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">taller_child</span>(<span class="hljs-params">self,cur_node</span>):</span>
        left=self.get_height(cur_node.left_child)
        right=self.get_height(cur_node.right_child)
        <span class="hljs-keyword">return</span> cur_node.left_child <span class="hljs-keyword">if</span> left&gt;=right <span class="hljs-keyword">else</span> cur_node.right_child
</code></pre>
<h3 id="heading-more-info-on-binary-search">More info on binary search:</h3>
<ul>
<li><a target="_blank" href="https://guide.freecodecamp.org/algorithms/search-algorithms/binary-search/">Binary search basics</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/binary-search-tree-what-is-it/">Binary search trees explained with examples</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/binary-data-structures-an-intro-to-trees-and-heaps-in-javascript-962ab536cb42/">Binary data structures: intro to trees (and heaps)</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Binary Search Tree Data Structure Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ A tree is a data structure composed of nodes that has the following characteristics: Each tree has a root node (at the top) having some value. The root node has zero or more child nodes. Each child node has zero or more child nodes, and so on. This ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/binary-search-tree-what-is-it/</link>
                <guid isPermaLink="false">66c3460cd48c8b932b406b12</guid>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data structures ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 22 Dec 2019 22:29:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9e86740569d1a4ca3d95.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A tree is a data structure composed of nodes that has the following characteristics:</p>
<ol>
<li>Each tree has a root node (at the top) having some value.</li>
<li>The root node has zero or more child nodes.</li>
<li>Each child node has zero or more child nodes, and so on. This create a subtree in the tree. Every node has it’s own subtree made up of his children and their children, etc. This means that every node on its own can be a tree.</li>
</ol>
<p>A binary search tree (BST) adds these two characteristics:</p>
<ol>
<li>Each node has a maximum of up to two children.</li>
<li>For each node, the values of its left descendent nodes are less than that of the current node, which in turn is less than the right descendent nodes (if any).</li>
</ol>
<p>The BST is built up on the idea of the <a target="_blank" href="https://guide.freecodecamp.org/algorithms/search-algorithms/binary-search">binary search</a> algorithm, which allows for fast lookup, insertion and removal of nodes. The way that they are set up means that, on average, each comparison allows the operations to skip about half of the tree, so that each lookup, insertion or deletion takes time proportional to the logarithm of the number of items stored in the tree, <code>O(log n)</code>. </p>
<p>However, some times the worst case can happen, when the tree isn’t balanced and the time complexity is <code>O(n)</code> for all three of these functions. That is why self-balancing trees (AVL, red-black, etc.) are a lot more effective than the basic BST.</p>
<p><strong>Worst case scenario example:</strong> This can happen when you keep adding nodes that are <em>always</em> larger than the node before (it’s parent), the same can happen when you always add nodes with values lower than their parents.</p>
<h2 id="heading-basic-operations-on-a-bst"><strong>Basic operations on a BST</strong></h2>
<ul>
<li>Create: creates an empty tree.</li>
<li>Insert: insert a node in the tree.</li>
<li>Search: Searches for a node in the tree.</li>
<li>Delete: deletes a node from the tree.</li>
</ul>
<h3 id="heading-create">Create</h3>
<p>Initially an empty tree without any nodes is created. The variable/identifier which must point to the root node is initialized with a <code>NULL</code> value.</p>
<h3 id="heading-search">Search</h3>
<p>You always start searching the tree at the root node and go down from there. You compare the data in each node with the one you are looking for. If the compared node doesn’t match then you either proceed to the right child or the left child, which depends on the outcome of the following comparison: If the node that you are searching for is lower than the one you were comparing it with, you proceed to to the left child, otherwise (if it’s larger) you go to the right child. Why? Because the BST is structured (as per its definition), that the right child is always larger than the parent and the left child is always lesser.</p>
<h3 id="heading-insert">Insert</h3>
<p>It is very similar to the search function. You again start at the root of the tree and go down recursively, searching for the right place to insert our new node, in the same way as explained in the search function. If a node with the same value is already in the tree, you can choose to either insert the duplicate or not. Some trees allow duplicates, some don’t. It depends on the certain implementation.</p>
<h3 id="heading-delete">Delete</h3>
<p>There are 3 cases that can happen when you are trying to delete a node. If it has,</p>
<ol>
<li>No subtree (no children): This one is the easiest one. You can simply just delete the node, without any additional actions required.</li>
<li>One subtree (one child): You have to make sure that after the node is deleted, its child is then connected to the deleted node’s parent.</li>
<li>Two subtrees (two children): You have to find and replace the node you want to delete with its successor (the letfmost node in the right subtree).</li>
</ol>
<p>The time complexity for creating a tree is <code>O(1)</code>. The time complexity for searching, inserting or deleting a node depends on the height of the tree <code>h</code>, so the worst case is <code>O(h)</code>.</p>
<h3 id="heading-predecessor-of-a-node">Predecessor of a node</h3>
<p>Predecessors can be described as the node that would come right before the node you are currently at. To find the predecessor of the current node, look at the right-most/largest leaf node in the left subtree.</p>
<h3 id="heading-successor-of-a-node">Successor of a node</h3>
<p>Successors can be described as the node that would come right after the node you are currently at. To find the successor of the current node, look at the left-most/smallest leaf node in the right subtree.</p>
<h2 id="heading-special-types-of-bt"><strong>Special types of BT</strong></h2>
<ul>
<li>Heap</li>
<li>Red-black tree</li>
<li>B-tree</li>
<li>Splay tree</li>
<li>N-ary tree</li>
<li>Trie (Radix tree)</li>
</ul>
<h2 id="heading-runtime">Runtime</h2>
<h3 id="heading-data-structure-array"><strong>Data structure: Array</strong></h3>
<ul>
<li>Worst-case performance: <code>O(log n)</code></li>
<li>Best-case performance: <code>O(1)</code></li>
<li>Average performance: <code>O(log n)</code></li>
<li>Worst-case space complexity: <code>O(1)</code></li>
</ul>
<p>Where <code>n</code> is the number of nodes in the BST.</p>
<h2 id="heading-implementation-of-bst">Implementation of BST</h2>
<p>Here’s a definiton for a BST node having some data, referencing to its left and right child nodes.</p>
<pre><code class="lang-c"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">node</span> {</span>
   <span class="hljs-keyword">int</span> data;
   <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">node</span> *<span class="hljs-title">leftChild</span>;</span>
   <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">node</span> *<span class="hljs-title">rightChild</span>;</span>
};
</code></pre>
<h3 id="heading-search-operation">Search Operation</h3>
<p>Whenever an element is to be searched, start searching from the root node. Then if the data is less than the key value, search for the element in the left subtree. Otherwise, search for the element in the right subtree. Follow the same algorithm for each node.</p>
<pre><code class="lang-c"><span class="hljs-function">struct node* <span class="hljs-title">search</span><span class="hljs-params">(<span class="hljs-keyword">int</span> data)</span></span>{
   <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">node</span> *<span class="hljs-title">current</span> = <span class="hljs-title">root</span>;</span>
   <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Visiting elements: "</span>);

   <span class="hljs-keyword">while</span>(current-&gt;data != data){

      <span class="hljs-keyword">if</span>(current != <span class="hljs-literal">NULL</span>) {
         <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d "</span>,current-&gt;data);

         <span class="hljs-comment">//go to left tree</span>
         <span class="hljs-keyword">if</span>(current-&gt;data &gt; data){
            current = current-&gt;leftChild;
         }<span class="hljs-comment">//else go to right tree</span>
         <span class="hljs-keyword">else</span> {                
            current = current-&gt;rightChild;
         }

         <span class="hljs-comment">//not found</span>
         <span class="hljs-keyword">if</span>(current == <span class="hljs-literal">NULL</span>){
            <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
         }
      }            
   }
   <span class="hljs-keyword">return</span> current;
}
</code></pre>
<h3 id="heading-insert-operation">Insert Operation</h3>
<p>Whenever an element is to be inserted, first locate its proper location. Start searching from the root node, then if the data is less than the key value, search for the empty location in the left subtree and insert the data. Otherwise, search for the empty location in the right subtree and insert the data.</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">insert</span><span class="hljs-params">(<span class="hljs-keyword">int</span> data)</span> </span>{
   <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">node</span> *<span class="hljs-title">tempNode</span> = (<span class="hljs-title">struct</span> <span class="hljs-title">node</span>*) <span class="hljs-title">malloc</span>(<span class="hljs-title">sizeof</span>(<span class="hljs-title">struct</span> <span class="hljs-title">node</span>));</span>
   <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">node</span> *<span class="hljs-title">current</span>;</span>
   <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">node</span> *<span class="hljs-title">parent</span>;</span>

   tempNode-&gt;data = data;
   tempNode-&gt;leftChild = <span class="hljs-literal">NULL</span>;
   tempNode-&gt;rightChild = <span class="hljs-literal">NULL</span>;

   <span class="hljs-comment">//if tree is empty</span>
   <span class="hljs-keyword">if</span>(root == <span class="hljs-literal">NULL</span>) {
      root = tempNode;
   } <span class="hljs-keyword">else</span> {
      current = root;
      parent = <span class="hljs-literal">NULL</span>;

      <span class="hljs-keyword">while</span>(<span class="hljs-number">1</span>) {                
         parent = current;

         <span class="hljs-comment">//go to left of the tree</span>
         <span class="hljs-keyword">if</span>(data &lt; parent-&gt;data) {
            current = current-&gt;leftChild;                
            <span class="hljs-comment">//insert to the left</span>

            <span class="hljs-keyword">if</span>(current == <span class="hljs-literal">NULL</span>) {
               parent-&gt;leftChild = tempNode;
               <span class="hljs-keyword">return</span>;
            }
         }<span class="hljs-comment">//go to right of the tree</span>
         <span class="hljs-keyword">else</span> {
            current = current-&gt;rightChild;

            <span class="hljs-comment">//insert to the right</span>
            <span class="hljs-keyword">if</span>(current == <span class="hljs-literal">NULL</span>) {
               parent-&gt;rightChild = tempNode;
               <span class="hljs-keyword">return</span>;
            }
         }
      }            
   }
}
</code></pre>
<p>Binary search trees (BSTs) also give us quick access to predecessors and successors. Predecessors can be described as the node that would come right before the node you are currently at.</p>
<ul>
<li>To find the predecessor of the current node, look at the rightmost/largest leaf node in the left subtree. Successors can be described as the node that would come right after the node you are currently at.</li>
<li>To find the successor of the current node, look at the leftmost/smallest leaf node in the right subtree.</li>
</ul>
<h2 id="heading-lets-look-at-a-couple-of-procedures-operating-on-trees">Let’s look at a couple of procedures operating on trees.</h2>
<p>Since trees are recursively defined, it’s very common to write routines that operate on trees that are themselves recursive.</p>
<p>So for instance, if we want to calculate the height of a tree, that is the height of a root node, We can go ahead and recursively do that, going through the tree. So we can say:</p>
<ul>
<li>For instance, if we have a nil tree, then its height is a 0.</li>
<li>Otherwise, We’re 1 plus the maximum of the left child tree and the right child tree.</li>
</ul>
<p>So if we look at a leaf for example, that height would be 1 because the height of the left child is nil, is 0, and the height of the nil right child is also 0. So the max of that is 0, then 1 plus 0.</p>
<h3 id="heading-heighttree-algorithm">Height(tree) algorithm</h3>
<pre><code class="lang-text">if tree = nil:
return 0
return 1 + Max(Height(tree.left),Height(tree.right))
</code></pre>
<h3 id="heading-here-is-the-code-in-c">Here is the code in C++</h3>
<pre><code class="lang-text">int maxDepth(struct node* node)
{
    if (node==NULL)
        return 0;
   else
   {
       int rDepth = maxDepth(node-&gt;right);
       int lDepth = maxDepth(node-&gt;left);

       if (lDepth &gt; rDepth)
       {
           return(lDepth+1);
       }
       else
       {
            return(rDepth+1);
       }
   }
}
</code></pre>
<p>We could also look at calculating the size of a tree that is the number of nodes.</p>
<ul>
<li>Again, if we have a nil tree, we have zero nodes.</li>
</ul>
<p>Otherwise, we have the number of nodes in the left child plus 1 for ourselves plus the number of nodes in the right child. So 1 plus the size of the left tree plus the size of the right tree.</p>
<h3 id="heading-sizetree-algorithm">Size(tree) algorithm</h3>
<pre><code class="lang-text">if tree = nil
return 0
return 1 + Size(tree.left) + Size(tree.right)
</code></pre>
<h3 id="heading-here-is-the-code-in-c-1">Here is the code in C++</h3>
<pre><code class="lang-text">int treeSize(struct node* node)
{
    if (node==NULL)
        return 0;
    else
        return 1+(treeSize(node-&gt;left) + treeSize(node-&gt;right));
}
</code></pre>
<h3 id="heading-relevant-videos-on-freecodecamp-youtube-channel"><strong>Relevant videos on freeCodeCamp YouTube channel</strong></h3>
<ul>
<li><a target="_blank" href="https://youtu.be/5cU1ILGy6dM">Binary Search Tree</a></li>
<li><a target="_blank" href="https://youtu.be/Aagf3RyK3Lw">Binary Search Tree: Traversal and Height</a></li>
</ul>
<h2 id="heading-following-are-common-types-of-binary-trees">Following are common types of Binary Trees:</h2>
<p>Full Binary Tree/Strict Binary Tree: A Binary Tree is full or strict if every node has exactly 0 or 2 children.</p>
<pre><code class="lang-text">           18
       /       \  
     15         30  
    /  \        /  \
  40    50    100   40
</code></pre>
<p>In Full Binary Tree, number of leaf nodes is equal to number of internal nodes plus one.</p>
<p>Complete Binary Tree: A Binary Tree is complete Binary Tree if all levels are completely filled except possibly the last level and the last level has all keys as left as possible</p>
<pre><code class="lang-text">           18
       /       \  
     15         30  
    /  \        /  \
  40    50    100   40
 /  \   /
8   7  9
</code></pre>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Red-Black Tree: Self-Balanced Binary Search Trees Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ What is a Red-Black Tree? Red-Black Tree is a type of self-balancing Binary Search Tree (BST). In a Red-Black Tree, every node follows these rules: Every node has two children, colored either red or black. Every tree leaf node is always black. Every... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/red-black-trees/</link>
                <guid isPermaLink="false">66c35dbbb8711219e1e72dda</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Computer Science ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 01 Dec 2019 18:40:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/01/red-black-tree.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-what-is-a-red-black-tree">What is a Red-Black Tree?</h2>
<p>Red-Black Tree is a type of self-balancing Binary Search Tree (BST). In a Red-Black Tree, every node follows these rules:</p>
<ol>
<li>Every node has two children, colored either red or black.</li>
<li>Every tree leaf node is always black.</li>
<li>Every red node has both of its children colored black.</li>
<li>There are no two adjacent red nodes (A red node cannot have a red parent or red child).</li>
<li>Every path from root to a tree leaf node has the same number of black nodes (called "black height").</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/2000px-Fibonacci_Tree_as_Red-Black_Tree.svg.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-inserting-into-red-black-trees">Inserting into Red-Black Trees</h3>
<p>A node is initially inserted into a Red-Black Tree just like any Binary Search Tree. The new node is then given a color of red. After that node has been inserted, the tree must be validated to ensure none of the five properties have been violated. If a property has been violated, there are three potential cases requiring either a left-rotation, right-rotation, and/or a recoloring of the nodes. The cases are dependent on the "uncle" of the current node. Specifically, whether the "uncle" node is black or red. For more info on inserting, the three cases can be found <a target="_blank" href="https://www.geeksforgeeks.org/red-black-tree-set-2-insert/">here</a>.</p>
<h3 id="heading-left-leaning-redblack-tree">Left-Leaning Red–Black Tree</h3>
<p>A left-leaning red–black (LLRB) tree is a type of self-balancing binary search tree. It is a variant of the red–black tree and guarantees the same asymptotic complexity for operations, but is designed to be easier to implement.</p>
<h3 id="heading-properties-of-left-leaning-red-black-trees">Properties of Left Leaning Red-Black Trees</h3>
<p>All of the red-black tree algorithms that have been proposed are characterized by a worst-case search time bounded by a small constant multiple of log N in a tree of N keys, and the behavior observed in practice is typically that same multiple faster than the worst-case bound, close to the optimal log N nodes examined that would be observed in a perfectly balanced tree.</p>
<p>Specifically, in a left-leaning red-black 2-3 tree built from N random keys: -&gt;A random successful search examines <code>log2 N</code> − 0.5 nodes. -&gt;The average tree height is about <code>2 log2 N</code></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ AVL Tree Insertion, Rotation, and Balance Factor Explained ]]>
                </title>
                <description>
                    <![CDATA[ What is an AVL Tree? An AVL tree is a type of binary search tree. Named after it's inventors Adelson, Velskii, and Landis, AVL trees have the property of dynamic self-balancing in addition to all the other properties exhibited by binary search trees.... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/avl-tree-insertion-rotation-and-balance-factor/</link>
                <guid isPermaLink="false">66c345265ced6d98e4bd3293</guid>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 23 Nov 2019 23:20:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9f18740569d1a4ca40ca.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-what-is-an-avl-tree">What is an AVL Tree?</h2>
<p>An AVL tree is a type of binary search tree. Named after it's inventors Adelson, Velskii, and Landis, AVL trees have the property of dynamic self-balancing in addition to all the other properties exhibited by binary search trees.</p>
<p>A BST is a data structure composed of nodes. It has the following guarantees:</p>
<ol>
<li>Each tree has a root node (at the top)</li>
<li>The root node has zero, one, or two child nodes</li>
<li>Each child node has zero, one, or two child nodes</li>
<li>Each node has up to two children</li>
<li>For each node, its left descendants are less than the current node, which is less than the right descendants</li>
</ol>
<p>AVL trees have an additional guarantee:</p>
<ol>
<li>The difference between the depth of right and left sub-trees cannot be more than one. This difference is called the balance factor.  </li>
</ol>
<p>In order to maintain this guarantee, an implementation of an AVL will include an algorithm to rebalance the tree when adding an additional element would upset this guarantee</p>
<p>AVL trees have a worst case lookup, insert, and delete time of <code>O(log n)</code>, where <code>n</code> is the number of nodes in the tree. The worst case space complexity is <code>O(n)</code>.</p>
<h3 id="heading-avl-insertion-process">AVL Insertion Process</h3>
<p>Insertion in an AVL tree is similar to insertion in a binary search tree. But after inserting and element, you need to fix the AVL properties using left or right rotations:</p>
<ul>
<li>If there is an imbalance in the left child's right sub-tree, perform a left-right rotation</li>
<li>If there is an imbalance in the left child's left sub-tree, perform a right rotation</li>
<li>If there is an imbalance in the right child's right sub-tree, perform a left rotation</li>
<li>If there is an imbalance in the right child's left sub-tree, perform a right-left rotation</li>
</ul>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/7m94k2Qhg68" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-avl-tree-rotations">AVL Tree Rotations</h2>
<p>In AVL trees, after each operation like insertion and deletion, the balance factor of every node needs to be checked. If every node satisfies the balance factor condition, then the operation can be concluded. Otherwise, the tree needs to be rebalanced using rotation operations.</p>
<p>There are four rotations and they are classified into two types: </p>
<h3 id="heading-left-rotation-ll-rotation">Left Rotation (LL Rotation)</h3>
<p>In left rotations, every node moves one position to left from the current position.</p>
<p><img src="https://raw.githubusercontent.com/HebleV/valet_parking/master/images/avl_left_rotation.jpg" alt="AVL Tree Left Rotation" width="500" height="185" loading="lazy"></p>
<h3 id="heading-right-rotation-rr-rotation">Right Rotation (RR Rotation)</h3>
<p>In right rotations, every node moves one position to right from the current position. </p>
<p><img src="https://raw.githubusercontent.com/HebleV/valet_parking/master/images/avl_right_rotation.jpg" alt="AVL Tree Right Rotation" width="500" height="181" loading="lazy"></p>
<h3 id="heading-left-right-rotation-lr-rotation">Left-Right Rotation (LR Rotation)</h3>
<p>Left-right rotations are a combination of a single left rotation followed by a single right rotation.  </p>
<p>First, every node moves one position to the left, then one position to the right from the current position. </p>
<h3 id="heading-right-left-rotation-rl-rotation">Right-Left Rotation (RL Rotation)</h3>
<p>Right-left rotations are a combination of a single right rotation followed by a single left rotation.</p>
<p>First, every node moves one position to the right then, then one position to the left from the current position.</p>
<h2 id="heading-application-of-avl-trees">Application of AVL Trees</h2>
<p>AVL trees are beneficial in cases like a database where insertions and deletions are not that frequent, but you frequently check for entries.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Binary Search Trees: BST Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ What is a Binary Search Tree? A tree is a data structure composed of nodes that has the following characteristics: Each tree has a root node at the top (also known as Parent Node) containing some value (can be any datatype). The root node has zero o... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/binary-search-trees-bst-explained-with-examples/</link>
                <guid isPermaLink="false">66c3460f622ca5970af832fc</guid>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data structures ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Trees ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 16 Nov 2019 17:58:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9f48740569d1a4ca41c4.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-what-is-a-binary-search-tree">What is a Binary Search Tree?</h2>
<p>A tree is a data structure composed of nodes that has the following characteristics:</p>
<ol>
<li>Each tree has a root node at the top (also known as Parent Node) containing some value (can be any datatype).</li>
<li>The root node has zero or more child nodes.</li>
<li>Each child node has zero or more child nodes, and so on. This creates a subtree in the tree. Every node has its own subtree made up of its children and their children, etc. This means that every node on its own can be a tree.</li>
</ol>
<p>A binary search tree (BST) adds these two characteristics:</p>
<ol>
<li>Each node has a maximum of up to two children.</li>
<li>For each node, the values of its left descendent nodes are less than that of the current node, which in turn is less than the right descendent nodes (if any).</li>
</ol>
<p>The BST is built on the idea of the <a target="_blank" href="https://guide.freecodecamp.org/algorithms/search-algorithms/binary-search">binary search</a> algorithm, which allows for fast lookup, insertion and removal of nodes. The way that they are set up means that, on average, each comparison allows the operations to skip about half of the tree, so that each lookup, insertion or deletion takes time proportional to the logarithm of the number of items stored in the tree,  <code>O(log n)</code> . However, some times the worst case can happen, when the tree isn't balanced and the time complexity is  <code>O(n)</code>  for all three of these functions. That is why self-balancing trees (AVL, red-black, etc.) are a lot more effective than the basic BST.</p>
<p><strong>Worst case scenario example:</strong>  This can happen when you keep adding nodes that are  <em>always</em>  larger than the node before (its parent), the same can happen when you always add nodes with values lower than their parents.</p>
<h3 id="heading-basic-operations-on-a-bst">Basic operations on a BST</h3>
<ul>
<li>Create: creates an empty tree.</li>
<li>Insert: insert a node in the tree.</li>
<li>Search: Searches for a node in the tree.</li>
<li>Delete: deletes a node from the tree.</li>
<li>Inorder: in-order traversal of the tree.</li>
<li>Preorder: pre-order traversal of the tree.</li>
<li>Postorder: post-order traversal of the tree.</li>
</ul>
<h4 id="heading-create">Create</h4>
<p>Initially an empty tree without any nodes is created. The variable/identifier which must point to the root node is initialized with a  <code>NULL</code>  value.</p>
<h4 id="heading-search">Search</h4>
<p>You always start searching the tree at the root node and go down from there. You compare the data in each node with the one you are looking for. If the compared node doesn't match then you either proceed to the right child or the left child, which depends on the outcome of the following comparison: If the node that you are searching for is lower than the one you were comparing it with, you proceed to the left child, otherwise (if it's larger) you go to the right child. Why? Because the BST is structured (as per its definition), that the right child is always larger than the parent and the left child is always lesser.</p>
<h6 id="heading-breadth-first-search-bfs">Breadth-first search (BFS)</h6>
<p>Breadth first search is an algorithm used to traverse a BST. It begins at the root node and travels in a lateral manner (side to side), searching for the desired node. This type of search can be described as O(n) given that each node is visited once and the size of the tree directly correlates to the length of the search.</p>
<h6 id="heading-depth-first-search-dfs">Depth-first search (DFS)</h6>
<p>With a Depth-first search approach, we start with the root node and travel down a single branch. If the desired node is found along that branch, great, but if not, continue upwards and search unvisited nodes. This type of search also has a big O notation of O(n).</p>
<h4 id="heading-insert">Insert</h4>
<p>It is very similar to the search function. You again start at the root of the tree and go down recursively, searching for the right place to insert our new node, in the same way as explained in the search function. If a node with the same value is already in the tree, you can choose to either insert the duplicate or not. Some trees allow duplicates, some don't. It depends on the certain implementation.</p>
<h4 id="heading-deletion">Deletion</h4>
<p>There are 3 cases that can happen when you are trying to delete a node. If it has,</p>
<ol>
<li>No subtree (no children): This one is the easiest one. You can simply just delete the node, without any additional actions required.</li>
<li>One subtree (one child): You have to make sure that after the node is deleted, its child is then connected to the deleted node's parent.</li>
<li>Two subtrees (two children): You have to find and replace the node you want to delete with its inorder successor (the leftmost node in the right subtree).</li>
</ol>
<p>The time complexity for creating a tree is  <code>O(1)</code> . The time complexity for searching, inserting or deleting a node depends on the height of the tree  <code>h</code> , so the worst case is  <code>O(h)</code>  in case of skewed trees.</p>
<h4 id="heading-predecessor-of-a-node">Predecessor of a node</h4>
<p>Predecessors can be described as the node that would come right before the node you are currently at. To find the predecessor of the current node, look at the right-most/largest leaf node in the left subtree.</p>
<h4 id="heading-successor-of-a-node">Successor of a node</h4>
<p>Successors can be described as the node that would come right after the the current node. To find the successor of the current node, look at the left-most/smallest leaf node in the right subtree.</p>
<h3 id="heading-special-types-of-bt">Special types of BT</h3>
<ul>
<li>Heap</li>
<li>Red-black tree</li>
<li>B-tree</li>
<li>Splay tree</li>
<li>N-ary tree</li>
<li>Trie (Radix tree)</li>
</ul>
<h3 id="heading-runtime">Runtime</h3>
<p><strong>Data structure: BST</strong></p>
<ul>
<li>Worst-case performance:  <code>O(n)</code></li>
<li>Best-case performance:  <code>O(1)</code></li>
<li>Average performance:  <code>O(log n)</code></li>
<li>Worst-case space complexity:  <code>O(1)</code></li>
</ul>
<p>Where  <code>n</code>  is the number of nodes in the BST. Worst case is O(n) since BST can be unbalanced.</p>
<h3 id="heading-implementation-of-bst">Implementation of BST</h3>
<p>Here's a definition for a BST node having some data, referencing to its left and right child nodes.</p>
<pre><code>struct node {
   int data;
   struct node *leftChild;
   struct node *rightChild;
};
</code></pre><h4 id="heading-search-operation">Search Operation</h4>
<p>Whenever an element is to be searched, start searching from the root node. Then if the data is less than the key value, search for the element in the left subtree. Otherwise, search for the element in the right subtree. Follow the same algorithm for each node.</p>
<pre><code>struct node* search(int data){
   struct node *current = root;
   printf(<span class="hljs-string">"Visiting elements: "</span>);

   <span class="hljs-keyword">while</span>(current-&gt;data != data){

      <span class="hljs-keyword">if</span>(current != NULL) {
         printf(<span class="hljs-string">"%d "</span>,current-&gt;data);

         <span class="hljs-comment">//go to left tree</span>
         <span class="hljs-keyword">if</span>(current-&gt;data &gt; data){
            current = current-&gt;leftChild;
         }<span class="hljs-comment">//else go to right tree</span>
         <span class="hljs-keyword">else</span> {                
            current = current-&gt;rightChild;
         }

         <span class="hljs-comment">//not found</span>
         <span class="hljs-keyword">if</span>(current == NULL){
            <span class="hljs-keyword">return</span> NULL;
         }
      }            
   }
   <span class="hljs-keyword">return</span> current;
}
</code></pre><h4 id="heading-insert-operation">Insert Operation</h4>
<p>Whenever an element is to be inserted, first locate its proper location. Start searching from the root node, then if the data is less than the key value, search for the empty location in the left subtree and insert the data. Otherwise, search for the empty location in the right subtree and insert the data.</p>
<pre><code><span class="hljs-keyword">void</span> insert(int data) {
   struct node *tempNode = (struct node*) malloc(sizeof(struct node));
   struct node *current;
   struct node *parent;

   tempNode-&gt;data = data;
   tempNode-&gt;leftChild = NULL;
   tempNode-&gt;rightChild = NULL;

   <span class="hljs-comment">//if tree is empty</span>
   <span class="hljs-keyword">if</span>(root == NULL) {
      root = tempNode;
   } <span class="hljs-keyword">else</span> {
      current = root;
      parent = NULL;

      <span class="hljs-keyword">while</span>(<span class="hljs-number">1</span>) {                
         parent = current;

         <span class="hljs-comment">//go to left of the tree</span>
         <span class="hljs-keyword">if</span>(data &lt; parent-&gt;data) {
            current = current-&gt;leftChild;                
            <span class="hljs-comment">//insert to the left</span>

            <span class="hljs-keyword">if</span>(current == NULL) {
               parent-&gt;leftChild = tempNode;
               <span class="hljs-keyword">return</span>;
            }
         }<span class="hljs-comment">//go to right of the tree</span>
         <span class="hljs-keyword">else</span> {
            current = current-&gt;rightChild;

            <span class="hljs-comment">//insert to the right</span>
            <span class="hljs-keyword">if</span>(current == NULL) {
               parent-&gt;rightChild = tempNode;
               <span class="hljs-keyword">return</span>;
            }
         }
      }            
   }
}
</code></pre><h4 id="heading-delete-operation">Delete Operation</h4>
<pre><code><span class="hljs-keyword">void</span> deleteNode(struct node* root, int data){

    <span class="hljs-keyword">if</span> (root == NULL) root=tempnode; 

    <span class="hljs-keyword">if</span> (data &lt; root-&gt;key) 
        root-&gt;left = deleteNode(root-&gt;left, key); 


    <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (key &gt; root-&gt;key) 
        root-&gt;right = deleteNode(root-&gt;right, key); 

    <span class="hljs-keyword">else</span>
    { 
        <span class="hljs-keyword">if</span> (root-&gt;left == NULL) 
        { 
            struct node *temp = root-&gt;right; 
            free(root); 
            <span class="hljs-keyword">return</span> temp; 
        } 
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (root-&gt;right == NULL) 
        { 
            struct node *temp = root-&gt;left; 
            free(root); 
            <span class="hljs-keyword">return</span> temp; 
        } 

        struct node* temp = minValueNode(root-&gt;right); 

        root-&gt;key = temp-&gt;key; 

        root-&gt;right = deleteNode(root-&gt;right, temp-&gt;key); 
    } 
    <span class="hljs-keyword">return</span> root; 

}
</code></pre><p>Binary search trees (BSTs) also give us quick access to predecessors and successors. Predecessors can be described as the node that would come right before the node you are currently at.</p>
<ul>
<li>To find the predecessor of the current node, look at the rightmost/largest leaf node in the left subtree. Successors can be described as the node that would come right after the node you are currently at.</li>
<li>To find the successor of the current node, look at the leftmost/smallest leaf node in the right subtree.</li>
</ul>
<h3 id="heading-lets-look-at-a-couple-of-procedures-operating-on-trees">Let's look at a couple of procedures operating on trees.</h3>
<p>Since trees are recursively defined, it's very common to write routines that operate on trees that are themselves recursive.</p>
<p>So for instance, if we want to calculate the height of a tree, that is the height of a root node, We can go ahead and recursively do that, going through the tree. So we can say:</p>
<ul>
<li>For instance, if we have a nil tree, then its height is a 0.</li>
<li>Otherwise, We're 1 plus the maximum of the left child tree and the right child tree.</li>
<li>So if we look at a leaf for example, that height would be 1 because the height of the left child is nil, is 0, and the height of the nil right child is also 0. So the max of that is 0, then 1 plus 0.</li>
</ul>
<h4 id="heading-heighttree-algorithm">Height(tree) algorithm</h4>
<pre><code><span class="hljs-keyword">if</span> tree = nil:
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
<span class="hljs-keyword">return</span> <span class="hljs-number">1</span> + Max(Height(tree.left),Height(tree.right))
</code></pre><h4 id="heading-here-is-the-code-in-c">Here is the code in C++</h4>
<pre><code>int maxDepth(struct node* node)
{
    <span class="hljs-keyword">if</span> (node==NULL)
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
   <span class="hljs-keyword">else</span>
   {
       int rDepth = maxDepth(node-&gt;right);
       int lDepth = maxDepth(node-&gt;left);

       <span class="hljs-keyword">if</span> (lDepth &gt; rDepth)
       {
           <span class="hljs-keyword">return</span>(lDepth+<span class="hljs-number">1</span>);
       }
       <span class="hljs-keyword">else</span>
       {
            <span class="hljs-keyword">return</span>(rDepth+<span class="hljs-number">1</span>);
       }
   }
}
</code></pre><p>We could also look at calculating the size of a tree that is the number of nodes.</p>
<ul>
<li>Again, if we have a nil tree, we have zero nodes.</li>
<li>Otherwise, we have the number of nodes in the left child plus 1 for ourselves plus the number of nodes in the right child. So 1 plus the size of the left tree plus the size of the right tree.</li>
</ul>
<h4 id="heading-sizetree-algorithm">Size(tree) algorithm</h4>
<pre><code><span class="hljs-keyword">if</span> tree = nil
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
<span class="hljs-keyword">return</span> <span class="hljs-number">1</span> + Size(tree.left) + Size(tree.right)
</code></pre><h4 id="heading-here-is-the-code-in-c-1">Here is the code in C++</h4>
<pre><code>int treeSize(struct node* node)
{
    <span class="hljs-keyword">if</span> (node==NULL)
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
    <span class="hljs-keyword">else</span>
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>+(treeSize(node-&gt;left) + treeSize(node-&gt;right));
}
</code></pre><h4 id="heading-traversal">Traversal</h4>
<p>There are 3 kinds of traversals that are done typically over a binary search tree. All these traversals have a somewhat common way of going over the nodes of the tree.</p>
<h5 id="heading-in-order">In-order</h5>
<p>This traversal first goes over the left subtree of the root node, then accesses the current node, followed by the right subtree of the current node. The code represents the base case too, which says that an empty tree is also a binary search tree.</p>
<pre><code><span class="hljs-keyword">void</span> inOrder(struct node* root) {
        <span class="hljs-comment">// Base case</span>
        <span class="hljs-keyword">if</span> (root == <span class="hljs-literal">null</span>) {
                <span class="hljs-keyword">return</span>;
        }
        <span class="hljs-comment">// Travel the left sub-tree first.</span>
        inOrder(root.left);
        <span class="hljs-comment">// Print the current node value</span>
        printf(<span class="hljs-string">"%d "</span>, root.data);
        <span class="hljs-comment">// Travel the right sub-tree next.</span>
        inOrder(root.right);
}
</code></pre><h3 id="heading-pre-order">Pre-order</h3>
<p>This traversal first accesses the current node value, then traverses the left and right sub-trees respectively.</p>
<pre><code><span class="hljs-keyword">void</span> preOrder(struct node* root) {
        <span class="hljs-keyword">if</span> (root == <span class="hljs-literal">null</span>) {
                <span class="hljs-keyword">return</span>;
        }
        <span class="hljs-comment">// Print the current node value</span>
        printf(<span class="hljs-string">"%d "</span>, root.data);
        <span class="hljs-comment">// Travel the left sub-tree first.</span>
        preOrder(root.left);
        <span class="hljs-comment">// Travel the right sub-tree next.</span>
        preOrder(root.right);
}
</code></pre><h3 id="heading-post-order">Post-order</h3>
<p>This traversal puts the root value at last, and goes over the left and right sub-trees first. The relative order of the left and right sub-trees remain the same. Only the position of the root changes in all the above mentioned traversals.</p>
<pre><code><span class="hljs-keyword">void</span> postOrder(struct node* root) {
        <span class="hljs-keyword">if</span> (root == <span class="hljs-literal">null</span>) {
                <span class="hljs-keyword">return</span>;
        }
        <span class="hljs-comment">// Travel the left sub-tree first.</span>
        postOrder(root.left);
        <span class="hljs-comment">// Travel the right sub-tree next.</span>
        postOrder(root.right);
        <span class="hljs-comment">// Print the current node value</span>
        printf(<span class="hljs-string">"%d "</span>, root.data);
}
</code></pre><h3 id="heading-relevant-videos-on-freecodecamp-youtube-channel">Relevant videos on freeCodeCamp YouTube channel</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/5cU1ILGy6dM" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-and-binary-search-tree-traversal-and-height">And Binary Search Tree: Traversal and Height</h2>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Aagf3RyK3Lw" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h3 id="heading-following-are-common-types-of-binary-trees">Following are common types of Binary Trees:</h3>
<p>Full Binary Tree/Strict Binary Tree: A Binary Tree is full or strict if every node has exactly 0 or 2 children.</p>
<pre><code>          <span class="hljs-number">18</span>
         /   \
       /       \  
     <span class="hljs-number">15</span>         <span class="hljs-number">30</span>  
    /  \       /  \
  <span class="hljs-number">40</span>    <span class="hljs-number">50</span>   <span class="hljs-number">100</span>   <span class="hljs-number">40</span>
</code></pre><p>In Full Binary Tree, number of leaf nodes is equal to number of internal nodes plus one.</p>
<p>Complete Binary Tree: A Binary Tree is complete Binary Tree if all levels are completely filled except possibly the last level and the last level has all keys as left as possible</p>
<pre><code>           <span class="hljs-number">18</span>
         /    \
       /        \  
     <span class="hljs-number">15</span>         <span class="hljs-number">30</span>  
    /  \       /  \
  <span class="hljs-number">40</span>    <span class="hljs-number">50</span>   <span class="hljs-number">100</span>   <span class="hljs-number">40</span>
 /  \   /
<span class="hljs-number">8</span>    <span class="hljs-number">7</span> <span class="hljs-number">9</span>
</code></pre><p>Perfect Binary Tree A Binary tree is Perfect Binary Tree in which all internal nodes have two children and all leaves are at the same level.</p>
<pre><code>          <span class="hljs-number">18</span>
         /  \
       /      \  
     <span class="hljs-number">15</span>        <span class="hljs-number">30</span>  
    /  \      /  \
  <span class="hljs-number">40</span>    <span class="hljs-number">50</span>  <span class="hljs-number">100</span>   <span class="hljs-number">40</span>
</code></pre><h3 id="heading-augmenting-a-bst">Augmenting a BST</h3>
<p>Sometimes we need to store some additional information with the traditional data structures to make our tasks easier. For example, consider a scenario where you are supposed to find the ith smallest number in a set. You can use brute force here but we can reduce the complexity of the problem to <code>O(lg n)</code> by augmenting a red-black or any self-balancing tree (where n is the number of elements in the set). We can also compute rank of any element in <code>O(lg n)</code> time. Let us consider a case where we are augmenting a red-black tree to store the additional information needed. Besides the usual attributes, we can store number of internal nodes in the subtree rooted at x(size of the subtree rooted at x including the node itself). Let x be any arbitrary node of a tree.</p>
<p><code>x.size = x.left.size + x.right.size + 1</code></p>
<p>While augmenting the tree, we should keep in mind, that we should be able to maintain the augmented information as well as do other operations like insertion, deletion, updating in <code>O(lg n)</code> time.</p>
<p>Since, we know that the value of x.left.size will give us the number of nodes which proceed x in the order traversal of the tree. Thus, <code>x.left.size + 1</code> is the rank of x within the subtree rooted at x.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A twisted tale of Binary Search ]]>
                </title>
                <description>
                    <![CDATA[ By Divya Godayal Awesome. That’s how I feel right now. Writing my first solo tech article. I must say I have a lot to share with you guys, and have a lot more to learn as well. So without any further ado, lets get to it. And yes, hold on ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-twisted-tale-of-binary-search-49f5ac01e83d/</link>
                <guid isPermaLink="false">66c34363160da468ed76f134</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 04 Jul 2018 00:33:07 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*DClFFS2kX-MPvGuHYvOyTw.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Divya Godayal</p>
<p>Awesome. That’s how I feel right now. Writing my first solo tech article.</p>
<p>I must say I have a lot to share with you guys, and have a lot more to learn as well. So without any further ado, lets get to it. And yes, hold on tight — ‘cause there is a twist in the tale. ?</p>
<h3 id="heading-binary-search">Binary Search</h3>
<p>All of us have heard of the classic <a target="_blank" href="https://www.geeksforgeeks.org/puzzle-set-35-2-eggs-and-100-floors/">2 Eggs and 100 Stories</a> problem. I have something similar for you.</p>
<p>You have a 100 story building with a rule:</p>
<p><code>**People with pets can only occupy top floors**</code></p>
<p>Your friend wishes to buy an apartment in this building. She is too scared of pets to live near them, but you love them. She asked if you can help her find out where exactly the pet friendly floors start. She wants to explore all of the different options available, and so you need to find out which floors starting from the ground up are the ones that don’t allow pets.</p>
<p>The building management folks are on a holiday. On every floor, there is a sign board next to the elevator telling you if the floor is pet friendly or not. But you are too lazy to stop at every floor to check the pet sign board since the lift is so slow.</p>
<p>What do you do?</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*mVvYhywAIoa11tCRfsHPQA.png" alt="Image" width="800" height="367" loading="lazy">
<em>The two possible sign boards. #GoRed is what your friend roots for.</em></p>
<p>The lift takes almost a minute at every floor to stop and then start again. Yes that’s how bad it is. But between the floors, navigation is pretty smooth. You have to get this done quickly.</p>
<p>How do you go about it ?</p>
<h3 id="heading-iterative-approach">Iterative approach</h3>
<p>One naïve approach to this would be to start at the very bottom of the building (the ground floor) and keep stopping the lift at every single floor to check the sign that floor has posted. You stop when you find the pet friendly sign.</p>
<p><strong>Best case</strong> is that the ground floor has the pet sign. Meaning the entire building has pets. No way your friend would buy an apartment here.</p>
<p><strong>Average case</strong> is that you go to the 50th floor, stopping at every floor in between, and finally find a pet sign board. So your friend can buy one from 1–49.</p>
<p><strong>Worst case</strong> scenario would be you reaching the 100th floor, stopping at every floor on the way up, only to find out that there are no pet sign boards in the entire building. So your friend can buy any apartment from 1–100, but who cares, it took you almost two hours to find that out. ? ?.</p>
<p>Algorithmically, given an array of 100 boolean values, the index of the array represents building floors and a 0 represents a floor where no pets are allowed while a 1 represents a floor where pets would be allowed. From the rule of the building, the array would be of the form</p>
<pre><code><span class="hljs-number">000.</span>.. <span class="hljs-number">1111.</span>..
</code></pre><p>that is, all 0s followed by all 1s, because only the top floors can be the ones where pets are allowed.</p>
<p>Given this array, we need to find the first index where there is a <code>1</code> . A linear search algorithm for this problem would be as simple as iterating over the array and looking for a <code>1</code> and returning when we find one.</p>
<p>As expected, the complexity of this algorithm would be <code>O(n)</code> where n = 100 for our specific building example. You need to come up with something faster than this. Stopping at every floor is not feasible, as it would take you a lot of time to cover the entire building in the worst case.</p>
<h3 id="heading-binary-search-approach">Binary Search Approach</h3>
<p>Let’s say you start from ground floor and got to the 50th floor with no stops. At the 50th floor, you stopped and got out of the lift and checked for the sign. The board sign said <code>“No Pets”</code>. This would mean that, until the 50th floor, there are definitely no pets.</p>
<p>So now knowing that you reduce your search space to the other half, which is floors 51–100. This means that with a single stop, you were able to cover half of the building knowing for sure that the first half doesn’t have any pets. That’s amazing!</p>
<p>Moving on, you again divide your remaining set of floors into half and take the lift and go directly to the 75th floor. And you see a <code>“Pets”</code> sign board there. This means the floor where it started showing up must be between 50–75. You can keep following a similar approach of diving the remaining floors into half and checking until you find the first floor with the <code>“Pets”</code> sign board.</p>
<p>You see, every time you make a decision, you divide your search space into two halves and go ahead with one half of the search space. That’s how we narrow down our search. Since we always divide the search space in two and choose one over the other, that is why this type of search strategy is called a <code>Binary</code> search strategy.</p>
<p>Isn’t that way faster?</p>
<p>Let’s look into the algorithm for this.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*5xqxb4gs88vQGaK8CCp47w.png" alt="Image" width="800" height="453" loading="lazy">
<em>Binary Search Algorithm</em></p>
<p>If you’ve been following along closely and have a grasp of the algorithm, you would have realized a hard and fast condition for the binary search algorithm to work. The condition is that the array needs to be sorted beforehand. In our example, the building floors were sorted from 1–100 and we could easily divide the search space in two.</p>
<p>Let’s look at an example array which is sorted and try and search for an element in it.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*sCdkKU8RqA6_R3uiy4nL2w.png" alt="Image" width="800" height="582" loading="lazy"></p>
<p>In the above example, the element to be searched is 8. The given array is a sorted array in increasing order. Once we find the middle element (which is 5), we see that the element to be searched is greater than the current index element. Since the array is sorted in increasing order, 8 would lie on the right of the array and can never be on the left side.</p>
<p>So we ignore the elements to the left of 5 and continue our search with the remaining elements, eventually finding out 8.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*S2lDovD5HeUsdSHm3NM4Sw.png" alt="Image" width="800" height="676" loading="lazy"></p>
<p>On the other hand, what if the array is not sorted? Even though we know the current element is 5 and we know we need to search for 8, we are not sure which direction is the right way to go. If we end up thinking the array is sorted and apply binary search and go to the right part, we will never find 8.</p>
<p><strong>So binary search essentially wants your array to be sorted.</strong></p>
<p>That was the standard binary search algorithm that we just looked at. But, as the title of the article suggests, there is a twist in the tale!</p>
<p>I am an avid competitive programmer, and there was an interesting variant of the binary search algorithm in the <a target="_blank" href="https://www.codechef.com/MAY18B/problems/FAKEBS">CodeChef May Long Challenge</a>.</p>
<p>Essentially, the Chef wrote the classic binary search, assuming the input array would be sorted. All the other children in the class copied the code from him, as Chef is the best programmer in the class. His assumption could’ve cost the entire class their assignment marks, as the input array was not sorted beforehand.</p>
<p>The only thing the Chef can do is to preprocess the array by swapping some pair of numbers here and there so that the binary search procedure still returns the right index.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*MOupjMd8PLQIkCoXHPIkHw.png" alt="Image" width="800" height="354" loading="lazy"></p>
<p><strong>Note:</strong> The preprocessor above should ideally return the modified array for the binary search to work correctly. However, as the problem statement asks, we are just trying to determine the number of swaps needed for binary search to work correctly on the unsorted array given an input. The algorithm would also return a -1 if such a modification is not possible for the given array and element.</p>
<p>The idea here is very simple.</p>
<p>We need to understand two basic steps. I call them the <strong>TI-ME</strong> steps. Perhaps that’ll help you remember what we are doing here.</p>
<p>a. <strong>T</strong>arget <strong>I</strong>ndex: The index of the element to be searched for. We need to know this, since this index would help us drive the modifications. Because every time we modify any element, we need to sail towards this index and not away from it.</p>
<p>b. <strong>M</strong>iddle <strong>E</strong>lement: If you look clearly in a binary search, it’s the middle element of the current search space which drives the next move. If this middle element takes us in the wrong direction, we need to replace with the appropriate element.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*xgnYQLeH-9l2MVU_OqTNLQ.png" alt="Image" width="800" height="278" loading="lazy">
<em>We are searching for 8 in the above unsorted array. We already saw in the examples above a normal binary search would fail for an unsorted array.</em></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*sJNU_8PdNlbIuy7RStVHdA.png" alt="Image" width="800" height="381" loading="lazy">
<em>Mid elements give direction to binary search. Middle element 5 would take binary search to go right. This way we would never find <code>8. If we swap 5 with an element greater than 8 we would force the search to go to left.</code></em></p>
<p>So, the whole idea here is that we swap all the middle elements which are wrongly placed.</p>
<p>The binary search algorithm (the value of the middle element with respect to the element to be searched, that is, X) can either take us towards the left half of the array or the right half. So, there are two possibilities for a wrongly placed middle element:</p>
<ol>
<li>The element to be searched was on the right of the middle element, but since <code>Element[Mid] &gt; Element[Target Ind</code>ex] , the binary search would have had to ignore the right half and move towards the left half. OR</li>
<li>The element to be searched was on the left of the middle element, but since <code>Element[Mid] &lt; Element[Target Ind</code>ex] , the binary search would have had to ignore the left half and move towards the right half.</li>
</ol>
<p>Therefore, if a middle element is wrongly placed such that a number <code>X</code> was needed in its place where <code>X &lt; Element[Target Ind</code>ex] , then we maintain a counter for that and call <code>it count_low_nee</code>ded .</p>
<p>Similarly, if a middle element is wrongly placed such that a number <code>X</code> was needed in its place where <code>X &gt; Element[Target Ind</code>ex] , then we maintain a counter for that and call <code>it count_high_nee</code>ded .</p>
<p>Also, if we simply run the binary search algorithm over the given array while searching for numbers, there would be some numbers that would be correctly placed. These would be the middle elements that drove the binary search in correct directions corresponding to the given element <code>X</code> (the element to be searched). These numbers cannot be a part of the swapping, because they are rightly positioned with respect to <code>X</code> .</p>
<p>Let’s look at the pseudo code for this algorithm first and then go through an example.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">can_preprocess</span>(<span class="hljs-params">arr, X</span>)</span>{     low = <span class="hljs-number">0</span>     high= <span class="hljs-number">0</span>
</code></pre><pre><code><span class="hljs-keyword">while</span> X is not found {          mid = (low + high) / <span class="hljs-number">2</span>          <span class="hljs-keyword">if</span> arr[mid] == X {             <span class="hljs-keyword">break</span>                     }
</code></pre><pre><code>correctly_placed_low = <span class="hljs-number">0</span>          correctly_placed_high = <span class="hljs-number">0</span>          count_low_needed = <span class="hljs-number">0</span>          count_high_needed = <span class="hljs-number">0</span>
</code></pre><pre><code><span class="hljs-keyword">if</span> <span class="hljs-string">`mid`</span> suggests we should go right <span class="hljs-keyword">for</span> X {               <span class="hljs-keyword">if</span> X is actually on the right {                   correctly_placed_low ++               }               <span class="hljs-keyword">else</span> {                   count_low_needed ++               }          } <span class="hljs-keyword">else</span> {               <span class="hljs-keyword">if</span> X is actually on the left {                  correctly_placed_high ++               }                <span class="hljs-keyword">else</span> {                  count_high_needed ++               }          }
</code></pre><pre><code>modify low and high according to           where <span class="hljs-string">`X`</span> actually is <span class="hljs-keyword">with</span> respect to <span class="hljs-string">`mid`</span>
</code></pre><pre><code>}
</code></pre><pre><code><span class="hljs-comment">// Total smaller numbers available for swapping     TSM = sorted_index[X] - correctly_placed_low</span>
</code></pre><pre><code><span class="hljs-comment">// Total Larger numbers available for swapping     TLM = (N - sorted_index[X]) - correctly_placed_high</span>
</code></pre><pre><code><span class="hljs-keyword">if</span> count_low_needed &gt; TSM or count_high_needed &gt; TLM {          <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>     }
</code></pre><pre><code><span class="hljs-keyword">return</span> max(count_low_needed, count_high_needed)
</code></pre><p><strong>NOTE:</strong> The problem statement fixes the input array for us and repeatedly passes values to be searched in the input array. So, we can iterate once over the original array to know the actual location of the element to be searched (create a dictionary, essentially).</p>
<p>Also, we need <code>sorted_index[X]</code> to tell us how many values are lesser than or greater than the element <code>X</code> in our array. We can sort the array and create another dictionary storing location of each element in the sorted array.</p>
<p>Let’s go through the steps of the proposed algorithm while dry running an example.</p>
<ol>
<li>Given an unsorted array, you need to search for <code>X = 4</code> .<br>Hence our target index is 7.</li>
</ol>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*3vnVPsJgCPjLLmWENiB8rQ.png" alt="Image" width="800" height="298" loading="lazy"></p>
<ol start="2">
<li>Mid element index &lt; Target Index, so we need to maneuver our search to the right half. B<code>ut Element[Mid] &gt; Element[Target</code> Index], <code>hence count_low_need</code>ed = 1</li>
</ol>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*goOz9sCtElJn8_GVf86n-Q.png" alt="Image" width="800" height="287" loading="lazy"></p>
<ol start="3">
<li>Mid element index &lt; Target Index, so we still need to maneuver our search to the right half. Once agai<code>n, Element[Mid] &gt; Element[Target</code> Index], <code>hence count_low_need</code>ed = 2</li>
</ol>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*RuHR_k66dh-G0KzI-6DRuQ.png" alt="Image" width="800" height="286" loading="lazy"></p>
<ol start="4">
<li>The total number of swaps needed for binary search to return the correct index here would be two swaps with elements lower than 4. We have smaller numbers <code>1, 3 or 2</code> for swapping available, so we can successfully do the swapping for this array so that binary search correctly finds out <code>4</code> .</li>
</ol>
<p>Below is the Python code for the given problem. Every step is explained in the comments.</p>
<p>The time complexity of this Twisted Binary Search algorithm is still <code>O(nlogn)</code> .</p>
<p>I hope you were able to grasp the inner workings of the binary search algorithm and had fun while going through this interesting problem as well. If you found this post useful, spread the love and share as much as possible. ?</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
