{"id":2546,"date":"2016-11-04T20:53:42","date_gmt":"2016-11-04T15:23:42","guid":{"rendered":"http:\/\/theoryofprogramming.azurewebsites.net\/?p=2546"},"modified":"2023-11-19T07:23:09","modified_gmt":"2023-11-19T07:23:09","slug":"binary-search-algorithm","status":"publish","type":"post","link":"https:\/\/theoryofcoding.com\/index.php\/2016\/11\/04\/binary-search-algorithm\/","title":{"rendered":"Binary Search Algorithm"},"content":{"rendered":"\n<p>Hello people&#8230;! In this post we will discuss one of the most commonly used search algorithm, the Binary Search.&nbsp;In a search algorithm,&nbsp;we are given an element and a collection or a set of elements. If the given element exists in the given set, we must return where it is located, or otherwise, if it does not exist, our algorithm must be able to say it does not exist.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Binary Search Conditions<\/h2>\n\n\n\n<p>The given set must obey the following rules if we want to apply binary search &#8211;<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>All pairs of elements in the given set must be comparable. Mathematically, this is called a totally ordered set.<\/li>\n\n\n\n<li>The given set must be sorted, in ascending or descending order.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Algorithm<\/h2>\n\n\n\n<p>Let&#8217;s say we are looking for 7 in an array A = {1, 2, 3, 4, 5, 6, 7, 8, 9}. Binary search&nbsp;compares the middle element (here 5) and the element to be searched (here 7). So, 5 is less than 7. Binary search says, &#8220;Okay so 5 is less than 7, so don&#8217;t bother about the elements left of 5 because they are less than 5 anyway. It will never be equal to 7. Continue the same job with the right half instead!&#8221;. So, now we will look at the elements right of 5 only.<\/p>\n\n\n\n<p>Now, let&#8217;s sat the middle element is 8. This time Binary Search says, &#8220;Elements right of 8 are more than 8, they will never be equal to 7, so neglect the elements right of 8, carry on with the elements left of 8.&#8221;<\/p>\n\n\n\n<p>So if you analyse this carefully, we are cutting the size of elements we are supposed to look at by half for each step.<\/p>\n\n\n\n<p>To implement this algorithm, we use 3 variables &#8211;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>low &#8211; the lowest index of the searching range.<\/li>\n\n\n\n<li>high &#8211; the highest index of the searching range.<\/li>\n\n\n\n<li>mid &#8211; which is calculated by the formula below<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"300\" height=\"61\" src=\"https:\/\/i0.wp.com\/theoryofprogramming.azurewebsites.net\/wp-content\/uploads\/2016\/11\/binary-search-equation-1-300x61.jpg?resize=300%2C61\" alt=\"binary-search-equation-1\" class=\"wp-image-2636\" srcset=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-equation-1.jpg?resize=300%2C61&amp;ssl=1 300w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-equation-1.jpg?resize=230%2C47&amp;ssl=1 230w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-equation-1.jpg?resize=350%2C72&amp;ssl=1 350w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-equation-1.jpg?w=450&amp;ssl=1 450w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" data-recalc-dims=\"1\" \/><\/figure>\n\n\n\n<p>Let us take the previous example array A = {1, 2, 3, 4, 5, 6, 7, 8, 9}. This time let us search for 9, and this time we will find the middle element using the formula above.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"1170\" height=\"507\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-1.jpg?resize=1170%2C507&#038;ssl=1\" alt=\"binary search\" class=\"wp-image-2582\" srcset=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-1.jpg?w=1235&amp;ssl=1 1235w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-1.jpg?resize=300%2C130&amp;ssl=1 300w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-1.jpg?resize=1024%2C444&amp;ssl=1 1024w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-1.jpg?resize=768%2C333&amp;ssl=1 768w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-1.jpg?resize=1000%2C433&amp;ssl=1 1000w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-1.jpg?resize=230%2C100&amp;ssl=1 230w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-1.jpg?resize=350%2C152&amp;ssl=1 350w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-1.jpg?resize=480%2C208&amp;ssl=1 480w\" sizes=\"auto, (max-width: 1170px) 100vw, 1170px\" data-recalc-dims=\"1\" \/><\/figure>\n\n\n\n<p>Initially, low = 0 and high = 8, which gives mid = 4. The middle element is not 9, but 5 which is less than 9, so we might find 9 only to the right of 5. So, we will assign low = mid + 1.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"1170\" height=\"511\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-2.jpg?resize=1170%2C511&#038;ssl=1\" alt=\"binary search\" class=\"wp-image-2583\" srcset=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-2.jpg?w=1249&amp;ssl=1 1249w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-2.jpg?resize=300%2C131&amp;ssl=1 300w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-2.jpg?resize=1024%2C448&amp;ssl=1 1024w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-2.jpg?resize=768%2C336&amp;ssl=1 768w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-2.jpg?resize=1000%2C437&amp;ssl=1 1000w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-2.jpg?resize=230%2C101&amp;ssl=1 230w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-2.jpg?resize=350%2C153&amp;ssl=1 350w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-2.jpg?resize=480%2C210&amp;ssl=1 480w\" sizes=\"auto, (max-width: 1170px) 100vw, 1170px\" data-recalc-dims=\"1\" \/><\/figure>\n\n\n\n<p>Now, low = 5 and high = 8, which gives mid = 6. Value 7 is less than 9, so we search in the right half of 7. We do this by low = mid + 1. (If we wanted to search in the left half, say for 6 example, we would do high = mid &#8211; 1).<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"1170\" height=\"629\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-3.jpg?resize=1170%2C629&#038;ssl=1\" alt=\"binary search\" class=\"wp-image-2584\" srcset=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-3.jpg?w=1223&amp;ssl=1 1223w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-3.jpg?resize=300%2C161&amp;ssl=1 300w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-3.jpg?resize=1024%2C550&amp;ssl=1 1024w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-3.jpg?resize=768%2C413&amp;ssl=1 768w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-3.jpg?resize=1000%2C537&amp;ssl=1 1000w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-3.jpg?resize=230%2C124&amp;ssl=1 230w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-3.jpg?resize=350%2C188&amp;ssl=1 350w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-3.jpg?resize=480%2C258&amp;ssl=1 480w\" sizes=\"auto, (max-width: 1170px) 100vw, 1170px\" data-recalc-dims=\"1\" \/><\/figure>\n\n\n\n<p>Even now, the middle element is less than the required element, so we must search in the right half. So we do low = mid + 1.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"1170\" height=\"609\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-4.jpg?resize=1170%2C609&#038;ssl=1\" alt=\"binary search\" class=\"wp-image-2585\" srcset=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-4.jpg?w=1296&amp;ssl=1 1296w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-4.jpg?resize=300%2C156&amp;ssl=1 300w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-4.jpg?resize=1024%2C533&amp;ssl=1 1024w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-4.jpg?resize=768%2C400&amp;ssl=1 768w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-4.jpg?resize=1000%2C521&amp;ssl=1 1000w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-4.jpg?resize=230%2C120&amp;ssl=1 230w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-4.jpg?resize=350%2C182&amp;ssl=1 350w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-4.jpg?resize=480%2C250&amp;ssl=1 480w\" sizes=\"auto, (max-width: 1170px) 100vw, 1170px\" data-recalc-dims=\"1\" \/><\/figure>\n\n\n\n<p>Now our middle element is equal to what we want, so we return this index! So basically Binary Search goes up to when there&#8217;s only one element left. If that remaining element is not the element we want, then we can claim that the given set does not contain it.<\/p>\n\n\n\n<p>Just imagine if we were searching for 10 in the above case, we would go up to the last element and find that even the last element is not equal to 10, so we return a -1 or some value which denotes that the element is not found.<\/p>\n\n\n\n<p>The reason the formula for calculating the middle element isn&#8217;t a simple average is to avoid an integer overflow error. If we try to calculate,<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"204\" height=\"92\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-equation-2.jpg?resize=204%2C92&#038;ssl=1\" alt=\"binary-search-equation-2\" class=\"wp-image-2631\" data-recalc-dims=\"1\"\/><\/figure>\n\n\n\n<p>when low and high are close to maximum values of an integer, they can cause an integer overflow. This is why we use the formula mentioned above.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Complexity<\/h2>\n\n\n\n<p>We make one comparison per iteration. So what is the worst case? Worst case occurs when the element is not present in the given set. Then we need to iterate until we have one element left. At each iteration, we reduce the range by half, so how many iterations should we perform to reach a single element?<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"1031\" height=\"504\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-complexity.png?resize=1031%2C504&#038;ssl=1\" alt=\"Binary Search complexity\" class=\"wp-image-2611\" srcset=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-complexity.png?w=1031&amp;ssl=1 1031w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-complexity.png?resize=300%2C147&amp;ssl=1 300w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-complexity.png?resize=1024%2C501&amp;ssl=1 1024w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-complexity.png?resize=768%2C375&amp;ssl=1 768w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-complexity.png?resize=1000%2C489&amp;ssl=1 1000w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-complexity.png?resize=230%2C112&amp;ssl=1 230w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-complexity.png?resize=350%2C171&amp;ssl=1 350w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2016\/11\/binary-search-complexity.png?resize=480%2C235&amp;ssl=1 480w\" sizes=\"auto, (max-width: 1031px) 100vw, 1031px\" data-recalc-dims=\"1\" \/><\/figure>\n\n\n\n<p>It is log<sub>2<\/sub> N! So the worst case complexity of binary search is O(log<sub>2<\/sub> N). The best case would be if the middle element of the set is itself is the value we want to find, then, the complexity would be O(1).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Code<\/h2>\n\n\n\n<p>It is a fairly simple algorithm to code. Please try to write the code by yourself. If you get stuck, you can use my code below as a reference.<\/p>\n\n\n<div class=\"su-tabs su-tabs-style-default su-tabs-mobile-stack\" data-active=\"1\" data-scroll-offset=\"0\" data-anchor-in-url=\"no\"><div class=\"su-tabs-nav\"><span class=\"\" data-url=\"\" data-target=\"blank\" tabindex=\"0\" role=\"button\">C<\/span><span class=\"\" data-url=\"\" data-target=\"blank\" tabindex=\"0\" role=\"button\">C++<\/span><span class=\"\" data-url=\"\" data-target=\"blank\" tabindex=\"0\" role=\"button\">Java<\/span><span class=\"\" data-url=\"\" data-target=\"blank\" tabindex=\"0\" role=\"button\">Python<\/span><\/div><div class=\"su-tabs-panes\"><div class=\"su-tabs-pane su-u-clearfix su-u-trim\" data-title=\"C\">\n<script src=\"https:\/\/gist.github.com\/VamsiSangam\/54d279c48aee7bf367e68b856de0ae89.js\"><\/script><br \/>\n<\/div>\n<div class=\"su-tabs-pane su-u-clearfix su-u-trim\" data-title=\"C++\">\n<script src=\"https:\/\/gist.github.com\/VamsiSangam\/f3f98ba3b1e9c4f4c6a9071a4160868c.js\"><\/script><br \/>\n<\/div>\n<div class=\"su-tabs-pane su-u-clearfix su-u-trim\" data-title=\"Java\">\n<script src=\"https:\/\/gist.github.com\/VamsiSangam\/8ec87cd501c4941ee21816af277ef33a.js\"><\/script><br \/>\n<\/div>\n<div class=\"su-tabs-pane su-u-clearfix su-u-trim\" data-title=\"Python\">\n<script src=\"https:\/\/gist.github.com\/VamsiSangam\/d9e8729ffdbe873489a6662a4adf9503.js\"><\/script><br \/>\n<\/div><\/div><\/div>\n\n\n\n<p>You can code the binary search using recursion too. But I prefer the iterative version as it does not have the recursion overhead and it will not produce a stack overflow error for large arrays.<\/p>\n\n\n\n<p>Keep practicing! Happy Coding! \ud83d\ude42<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello people&#8230;! In this post we will discuss one of the most commonly used search algorithm, the Binary Search.&nbsp;In a search algorithm,&nbsp;we [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[12],"tags":[30],"class_list":["post-2546","post","type-post","status-publish","format-standard","hentry","category-searching-algorithms","tag-binary-search"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts\/2546","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/comments?post=2546"}],"version-history":[{"count":1,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts\/2546\/revisions"}],"predecessor-version":[{"id":3871,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts\/2546\/revisions\/3871"}],"wp:attachment":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/media?parent=2546"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/categories?post=2546"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/tags?post=2546"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}