<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adarsh Gupta on Medium]]></title>
        <description><![CDATA[Stories by Adarsh Gupta on Medium]]></description>
        <link>https://medium.com/@adarshguptamaurya?source=rss-4a5f05b43900------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*z82dJ_WXWRUm-P4S.</url>
            <title>Stories by Adarsh Gupta on Medium</title>
            <link>https://medium.com/@adarshguptamaurya?source=rss-4a5f05b43900------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:01:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adarshguptamaurya/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What is Binary Search?! Lets Understand]]></title>
            <link>https://medium.com/@adarshguptamaurya/what-is-binary-search-lets-understand-f5ab55cccbe2?source=rss-4a5f05b43900------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5ab55cccbe2</guid>
            <category><![CDATA[time-complexity]]></category>
            <category><![CDATA[divide-and-conquer]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[search]]></category>
            <dc:creator><![CDATA[Adarsh Gupta]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 03:18:26 GMT</pubDate>
            <atom:updated>2023-04-02T06:37:45.713Z</atom:updated>
            <content:encoded><![CDATA[<p>Binary search is a powerful algorithm in computer science, primarily used to search for a specific item in a sorted array or list. It is a divide-and-conquer algorithm, which means it recursively breaks down the problem into smaller subproblems until the desired result is obtained. Binary search is a fast and efficient algorithm with a time complexity of O(log n), where n is the size of the array. In this blog, we will explore how binary search works, its advantages, and its limitations with python code and algorithm so that you can impress someone with your knowledge of binary search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPR7lthCPNdyksIT6MPPig.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSYYg1ViXzYWsoKB7-L9Uw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ScQzm3UaTmpLtOO7ZobLHQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y7rnHqy3dqtEWKU47JJPqg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qUn5ZFoG6jcw9_KFmOttOQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*boFmpF76e_5trEGCRsPVqA.jpeg" /></figure><ol><li><strong>Efficiency</strong>: Binary search is an efficient algorithm that can search through a sorted array of n elements in O(log n) time. This makes it faster than linear search, which takes O(n) time.</li><li><strong>Simplicit</strong>y: Binary search is a simple algorithm to implement and understand. It follows a straightforward divide-and-conquer approach, where the search space is recursively divided into two halves.</li><li><strong>Versatility</strong>: Binary search can be applied to a wide range of problems beyond just searching for an element in an array. It can be used to find the minimum or maximum element in a range, count the number of occurrences of an element in an array, and even find a particular value in a two-dimensional matrix.</li><li><strong>Scalability</strong>: Binary search works well on large datasets, and its efficiency makes it a useful tool in cases where time and memory are limited resources.</li><li><strong>Accuracy</strong>: Binary search guarantees finding the target element if it is present in the array. Additionally, it provides the index of the element in the array, which can be useful in further processing.</li><li><strong>Memory efficiency</strong>: Binary search only requires storing the indices of the start and end of the search range and the index of the middle element. This makes it memory-efficient compared to other search algorithms that require extra data structures to be stored.</li></ol><h3>Limitations of Binary Search Algorithm</h3><ol><li><strong>Requires a sorted arra</strong>y: Binary search only works on sorted arrays. If the array is not sorted, binary search cannot be used to find the target element.</li><li><strong>Limited to one-dimensional arrays</strong>: Binary search is limited to one-dimensional arrays. It cannot be used to search for elements in multi-dimensional arrays or other data structures.</li><li><strong>Not always faster than linear search</strong>: While binary search is generally faster than linear search, there are cases where linear search can be more efficient. For example, when searching for a small number of elements in an unsorted array, a linear search may be faster than the cost of sorting the array for a binary search.</li></ol><h3>Application of Binary Search</h3><ol><li><strong>Search in Databases</strong>: Binary search is used in many database management systems to quickly search for a specific record. In a large database, a binary search algorithm can significantly reduce the search time.</li><li><strong>E-commerce</strong>: E-commerce websites often use binary search to help users search for products. When a user enters a search query, binary search is used to quickly find the relevant products from a large database.</li><li><strong>Spell Checking</strong>: Binary search is used in spell-checking algorithms to search for words in a dictionary. This helps to suggest the correct spelling of a word when a user enters an incorrect spelling.</li><li><strong>Finance</strong>: Binary search is used in finance to search for the optimal solution of a problem, such as maximizing the return on investment or minimizing the risk.</li><li><strong>Game Development</strong>: In game development, binary search is used to search for objects or elements in the game. It is also used to sort and search through large amounts of game data.</li><li><strong>Genetics</strong>: Binary search is used in genetics to search for specific sequences of DNA. The search algorithm can quickly identify the location of a specific gene or sequence in the DNA.</li></ol><p>Not to understand how binary search works let&#39;s first understand the pseudocode of binary search in plain English and then I will explain each step of the pseudocode to you.</p><h3>Pseudocode Binary Search</h3><pre>1. Let the array be sorted in ascending order<br>2. Set low to the first index of the array<br>3. Set high to the last index of the array<br>4. While low is less than or equal to high<br>   5. Set mid to the middle index of the array<br>   6. If the element at mid is equal to the target element, return mid<br>   7. If the element at mid is less than the target element, set low to mid + 1<br>   8. If the element at mid is greater than the target element, set high to mid - 1<br>9. If the target element is not found, return -1</pre><p><strong>Explanation of the Pseudocode:</strong></p><p>Binary search is a search algorithm that finds the position of a target element within a sorted array. The algorithm works by repeatedly dividing the search interval in half until the target element is found, or the search interval is empty. The pseudocode above outlines the basic steps of the binary search algorithm.</p><p>The algorithm starts by assuming that the input array is sorted in ascending order. It then sets the search interval, represented by two indices, low and high, to cover the entire array.</p><p>The algorithm then enters a loop that continues until the search interval is empty or the target element is found. On each iteration, the algorithm calculates the middle index of the search interval, represented by mid. It then compares the element at mid with the target element.</p><p>If the element at mid is equal to the target element, the algorithm returns, indicating that the element was found. Otherwise, if the element at mid is less than the target element, the search interval is narrowed to the upper half of the array. If the element at mid is greater than the target element, the search interval is narrowed to the lower half of the array.</p><p>The algorithm continues to divide the search interval in half until the target element is found or the search interval is empty. If the target element is not found, the algorithm returns -1 to indicate that the element was not present in the array.</p><h3>Binary Search Algorithm</h3><p>There are generally 2 approaches that the world follows to implement the binary search, the first one is the iterative approach and the second one is the recursive approach.</p><h3>Iterative approach</h3><pre>binarySearch(arr, size)<br>		   loop until beg is not equal to end<br>    midIndex = (beg + end)/2<br>    if (item == arr[midIndex] )<br>        return midIndex<br>    else if (item &gt; arr[midIndex] ) <br>        beg = midIndex + 1<br>    else                       <br>        end = midIndex - 1</pre><p>In this approach, we generally do all the calculations or logic implementation in the loop function which happens again and again thats why it is known as interactive which means the logic will run again and again until the desired condition is not met.</p><h3>Recursive approach</h3><pre>binarySearch(arr, item, beg, end)<br>    if beg&lt;=end<br>        midIndex = (beg + end) / 2 <br>        if item == arr[midIndex]<br>            return midIndex<br>        else if item &lt; arr[midIndex]        <br>            return binarySearch(arr, item, midIndex + 1, end)<br>        else                              <br>            return binarySearch(arr, item, beg, midIndex - 1)<br>    <br>    return -1</pre><p>In this approach, we generally do all the calculations or logic implementation by calling the parent function again and again in recursion and have an exit condition when the desired result is found that is why it is known as the recursive approach</p><h3>Binary Search Algorithm dry run</h3><p>Let&#39;s visualize binary search algorithm using the input array [1, 2, 3, 4, 5, 6, 7,8,9,10] and searching for the target value 6:</p><p><strong>This GIF will clear your understanding furthermore</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NzFnopBV1HwpPTWEkFMytg.gif" /><figcaption>This visualization was created with the help of <a href="https://chiranjeevikarthik.me/Algovis/algorithms/searching/binary">Algovis</a> website</figcaption></figure><ol><li>Initialize the search interval: beg = 0 and end = 9 (since the list has 10 elements).</li><li>Calculate the middle index of the search interval: midIndex = (beg + end) // 2 = 4.</li><li>Check if the target element, 6, is equal to the element at the middle index, which is 5. Since they are not equal, we move on to the next step.</li><li>Check if the target element, 6, is greater than the element at the middle index, which is 5. Since 6 is greater than 5, we narrow the search interval to the upper half of the list: beg = midIndex + 1 = 5 and end remains 9.</li><li>Calculate the new middle index of the search interval: midIndex = (beg + end) // 2 = 7.</li><li>Check if the target element, 6, is equal to the element at the middle index, which is 7. Since they are not equal, we move on to the next step.</li><li>Check if the target element, 6, is less than the element at the middle index, which is 7. Since 6 is less than 7, we narrow the search interval to the lower half of the upper half: beg remains 5 and end = midIndex - 1 = 6.</li><li>Calculate the new middle index of the search interval: midIndex = (beg + end) // 2 = 5.</li><li>Check if the target element, 6, is equal to the element at the middle index, which is 6. Since they are equal, we have found the target element.</li><li>Return the index of the target element, which is midIndex = 5.</li></ol><p>Therefore, the binary search algorithm successfully found the target element, 6, in the list and returned its index, which is 5.</p><h3>Binary Search Time Complexity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Xe8MHItv7IvIs2wM1mi8A.jpeg" /></figure><p>The algorithm works by halving the search interval in each iteration, reducing the search space exponentially. As a result, even for very large arrays, binary search can find the target element very quickly. In the worst-case scenario, the target element is not present in the array, and the algorithm will continue to divide the search interval in half until it reaches a size of 1.</p><p>The number of times the search interval can be divided in half before it reaches a size of 1 is log2(n). Therefore, the time complexity of the binary search is O(log n). This is a very fast search time, even for very large arrays.</p><p>In practical terms, this means that binary search can be used to efficiently search very large arrays. For example, searching a sorted array of one billion elements would take at most log2(10^9) = 30 iterations, which is a very fast search time.</p><ul><li><strong>Best case</strong>: O(1) - This occurs when the target element is located in the middle of the array, and the search is successful after just one comparison.</li><li><strong>Worst case</strong>: O(log n) - This occurs when the target element is not present in the array, and the search has to go through all the elements in the array. In this case, the search interval is divided in half repeatedly until it reaches a size of 1.</li><li><strong>Average case</strong>: O(log n) - This assumes that the probability of finding the target element is the same for all elements in the array. In this case, the number of iterations required to find the target element is roughly proportional to the logarithm of the size of the input array.</li></ul><h3>Calculating the Time complexity of binary search</h3><p>Let’s say the array has n elements and the algorithm terminates after k iterations.</p><p>At each iteration, the array is divided by half, so the length of the array becomes n/2, n/2^2, n/2^3, ..., n/2^k.</p><p>After k divisions, the length of the array becomes 1, so n/2^k = 1 =&gt; n = 2^k.</p><p>Applying the log function on both sides: log2(n) = log2(2^k) =&gt; log2(n) = k log2(2).</p><p>As log2(2) = 1, we get k = log2(n).</p><p>Therefore, the time complexity of the binary search is log2(n), which is a very efficient algorithm.</p><h3>Binary Search Space Complexity</h3><p>The binary search algorithm can be implemented in two ways: iterative and recursive. The space complexity of the algorithm depends on the method of implementation.</p><p><strong>Iterative method:</strong> The algorithm traverses through the sorted array and compares the middle element with the target element until the target element is found or the entire array has been searched. This method has a space complexity of O(1) since no auxiliary space is needed.</p><p><strong>Recursive method:</strong> has a space complexity of O(log n) since the new values are passed to the next recursion of the loop. In this method, the maximum and minimum values are used as the boundary condition, and the algorithm uses recursion to search for the target element. Each recursive call to the algorithm creates a new stack frame, which increases the space complexity. However, as the algorithm narrows down its search by half at each recursion, it takes O(log n) space complexity to execute.</p><h3>Binary Search in Python</h3><p>So I will show you two different implementations of the binary search first iterative and the second recursive way. I will also add comments in the code and explain each line of the code</p><h3>Iterative Binary Search in Python</h3><p><strong>code:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d6d369a8e2ae4e65a597e2c0eb1476f/href">https://medium.com/media/2d6d369a8e2ae4e65a597e2c0eb1476f/href</a></iframe><p>The code defines a function binary_search_iterative that takes two parameters: an array arr and a target value target. The function performs a binary search on the array to find the target value and returns the index of the target value if it is found, or -1 if it is not found.</p><p>The function starts by defining two pointers: left and right. left is initialized to 0, and right is initialized to the index of the last element in the array.</p><p>The function then enters a while loop that continues as long as left is less than or equal to right. Inside the loop, the function calculates the index of the middle element using integer division (//) and the formula (left + right) // 2.</p><p>The function then checks whether the middle element is equal to the target value. If it is, the function returns the index of the middle element.</p><p>If the middle element is greater than the target value, the function updates the right pointer to be one index less than the middle index, effectively discarding the right half of the array.</p><p>If the middle element is less than the target value, the function updates the left pointer to be one index greater than the middle index, effectively discarding the left half of the array.</p><p>The function continues to loop, discarding half of the remaining array each time until the target value is found or left becomes greater than right.</p><p>If the target value is not found, the function returns -1.</p><h3>Recursive Binary Search in Python</h3><p><strong>code:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fd8d4f9868f890ec5ca2b236d7520e3/href">https://medium.com/media/9fd8d4f9868f890ec5ca2b236d7520e3/href</a></iframe><p>In the above code, we have defined a function binary_search() which takes four arguments:</p><ul><li>arr: a sorted array of integers to search for an element</li><li>l: the leftmost index of the array</li><li>r: the rightmost index of the array</li><li>x: the element to search in the array</li></ul><p>Firstly, we check if the right index is greater than or equal to the left index. If the condition is satisfied, we find the mid-index of the array using the formula mid = l + (r - l) // 2. Here, we have used // an operator for integer division to ensure that mid is an integer.</p><p>Then we check if the mid element is equal to the search element x. If it’s true, then we return the mid-index. Otherwise, if the mid element is greater than the search element, then the search element must be in the left subarray. We recursively call the binary_search() function on the left subarray. Similarly, if the mid element is less than the search element, then the search element must be in the right subarray. We recursively call the binary_search() function on the right subarray.</p><p>If the condition r &gt;= l is not satisfied, it means that the element is not present in the array, and we return -1.</p><p>Overall, the space complexity of the recursive approach of Binary Search is O(log n), where n is the size of the array, as the maximum number of function calls that can be stored on the call stack is log n.</p><h3>Conclusion</h3><p>In conclusion, the Binary Search Algorithm is a fundamental search algorithm that is widely used in computer science and data analysis. It is an efficient algorithm that can be used to search for a specific value in a sorted dataset, making it suitable for a variety of applications. From searching for a specific word in a dictionary to finding a name in a phonebook, Binary Search can save time and reduce complexity. By understanding the working of this algorithm and its implementation in various programming languages, you can enhance your skills as a programmer or data analyst. It is important to remember that with practice and experience, you can become more proficient in using Binary Search to solve real-world problems.</p><h3>References</h3><ol><li>This blog was inspired by <a href="https://www.mygreatlearning.com/blog/binary-search-algorithm/">Binary Search Algorithm</a> by <a href="https://www.mygreatlearning.com/blog/author/faizanparvez/">Faizan Parvez</a></li><li>All the images were created using <a href="https://labs.openai.com/">DALL-E</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5ab55cccbe2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>