{"id":24959,"date":"2017-10-15T13:54:41","date_gmt":"2017-10-15T08:24:41","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=24959"},"modified":"2017-10-15T13:54:41","modified_gmt":"2017-10-15T08:24:41","slug":"binary-search-2","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/binary-search-2\/","title":{"rendered":"Binary Search"},"content":{"rendered":"<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>Given a sorted array arr[] of n elements, write a function to search a given element x in arr[].<\/p>\n<p>A simple approach is to do linear search.The time complexity of above algorithm is O(n). Another approach to perform the same task is using Binary Search.<\/p>\n<p><strong>Binary Search:<\/strong> Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.<\/p>\n<p>Example:<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-24962\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/binary-search.png\" alt=\"Binary Search\" width=\"693\" height=\"313\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/binary-search.png 693w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/binary-search-300x135.png 300w\" sizes=\"(max-width: 693px) 100vw, 693px\" \/><\/p>\n<p>c and c++<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">c and c++<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">#include &lt;stdio.h&gt;<br\/> <br\/>\/\/ A recursive binary search function. It returns location of x in<br\/>\/\/ given array arr[l..r] is present, otherwise -1<br\/>int binarySearch(int arr[], int l, int r, int x)<br\/>{<br\/>   if (r &gt;= l)<br\/>   {<br\/>        int mid = l + (r - l)\/2;<br\/> <br\/>        \/\/ If the element is present at the middle itself<br\/>        if (arr[mid] == x)  return mid;<br\/> <br\/>        \/\/ If element is smaller than mid, then it can only be present<br\/>        \/\/ in left subarray<br\/>        if (arr[mid] &gt; x) return binarySearch(arr, l, mid-1, x);<br\/> <br\/>        \/\/ Else the element can only be present in right subarray<br\/>        return binarySearch(arr, mid+1, r, x);<br\/>   }<br\/> <br\/>   \/\/ We reach here when element is not present in array<br\/>   return -1;<br\/>}<br\/> <br\/>int main(void)<br\/>{<br\/>   int arr[] = {2, 3, 4, 10, 40};<br\/>   int n = sizeof(arr)\/ sizeof(arr[0]);<br\/>   int x = 10;<br\/>   int result = binarySearch(arr, 0, n-1, x);<br\/>   (result == -1)? printf(&quot;Element is not present in array&quot;)<br\/>                 : printf(&quot;Element is present at index %d&quot;, result);<br\/>   return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Output<\/p>\n<p>Element is present at index 3<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>Python<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">python<\/span> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Iterative Binary Search Function<br\/># It returns location of x in given array arr if present,<br\/># else returns -1<br\/>def binarySearch(arr, l, r, x):<br\/> <br\/>    while l &lt;= r:<br\/> <br\/>        mid = l + (r - l)\/2;<br\/>         <br\/>        # Check if x is present at mid<br\/>        if arr[mid] == x:<br\/>            return mid<br\/> <br\/>        # If x is greater, ignore left half<br\/>        elif arr[mid] &lt; x:<br\/>            l = mid + 1<br\/> <br\/>        # If x is smaller, ignore right half<br\/>        else:<br\/>            r = mid - 1<br\/>     <br\/>    # If we reach here, then the element was not present<br\/>    return -1<br\/> <br\/> <br\/># Test array<br\/>arr = [ 2, 3, 4, 10, 40 ]<br\/>x = 10<br\/> <br\/># Function call<br\/>result = binarySearch(arr, 0, len(arr)-1, x)<br\/> <br\/>if result != -1:<br\/>    print &quot;Element is present at index %d&quot; % result<br\/>else:<br\/>    print &quot;Element is not present in array&quot;<\/code><\/pre> <\/div>\n<p>Output<\/p>\n<p>Element is present at index 3<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>Java<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java implementation of iterative Binary Search<br\/>class BinarySearch<br\/>{<br\/>    \/\/ Returns index of x if it is present in arr[], else<br\/>    \/\/ return -1<br\/>    int binarySearch(int arr[], int x)<br\/>    {<br\/>        int l = 0, r = arr.length - 1;<br\/>        while (l &lt;= r)<br\/>        {<br\/>            int m = l + (r-l)\/2;<br\/> <br\/>            \/\/ Check if x is present at mid<br\/>            if (arr[m] == x)<br\/>                return m;<br\/> <br\/>            \/\/ If x greater, ignore left half<br\/>            if (arr[m] &lt; x)<br\/>                l = m + 1;<br\/> <br\/>            \/\/ If x is smaller, ignore right half<br\/>            else<br\/>                r = m - 1;<br\/>        }<br\/> <br\/>        \/\/ if we reach here, then element was not present<br\/>        return -1;<br\/>    }<br\/> <br\/>    \/\/ Driver method to test above<br\/>    public static void main(String args[])<br\/>    {<br\/>        BinarySearch ob = new BinarySearch();<br\/>        int arr[] = {2, 3, 4, 10, 40};<br\/>        int n = arr.length;<br\/>        int x = 10;<br\/>        int result = ob.binarySearch(arr, x);<br\/>        if (result == -1)<br\/>            System.out.println(&quot;Element not present&quot;);<br\/>        else<br\/>            System.out.println(&quot;Element found at index &quot;+result);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p>Output<\/p>\n<p>Element is present at index 3<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Time Complexity:<\/strong><\/p>\n<p>The time complexity of Binary Search can be written as<\/p>\n<p>T(n) = T(n\/2) + c<\/p>\n<p>The above recurrence can be solved either using Recurrence T ree method or Master method. It falls in case II of Master Method and solution of the recurrence is <img decoding=\"async\" class=\"ql-img-inline-formula quicklatex-auto-format\" title=\"Rendered by QuickLaTeX.com\" src=\"http:\/\/www.geeksforgeeks.org\/wp-content\/ql-cache\/quicklatex.com-e2fe30ce8f470a20f455b3f5dfcc5afc_l3.svg\" alt=\"\\Theta(Logn)\" width=\"67\" height=\"18\" \/>.<\/p>\n<p><strong>Auxiliary Space:<\/strong> O(1) in case of iterative implementation. In case of recursive implementation, O(Logn) recursion call stack space.<\/p>\n<p><strong>Algorithmic Paradigm:<\/strong> Divide and Conquer.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Binary Search &#8211; search and sorting &#8211; Search a sorted array by dividing the search interval in half. Begin with an interval covering the whole array.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[80126,1],"tags":[70276,70283,70319,70078,70096,70293,70289,70190,70299,70052,70264,70282,70304,70109,70076,70107,70120,70301,70081,70090,70082,70270,70113,70322,70088,70269,70309,70275,70295,70086,70265,70320,70321,70115,70307,70278,70297,70310,70263,70281,70279,70300,70284,70318,70277,70294,70098,70314,70305,70273,70316,70268,70287,70296,70303,70291,70288,70285,70312,70298,70311,70116,70028,70306,70271,63929,23950,70274,70290,70069,70063,70060,70262,70266,70286,70292,70272,62569,70099,70267,70280,70097,70315,70308,70261,70317,70026,23955,70302,70313],"class_list":["post-24959","post","type-post","status-publish","format-standard","hentry","category-binary-search-tree","category-coding","tag-algorithm-for-binary-search","tag-algorithm-of-binary-search","tag-applications-of-binary-search","tag-array-search","tag-arrays-binarysearch","tag-audio-search-engine","tag-balanced-binary-tree","tag-binary","tag-binary-compound","tag-binary-search","tag-binary-search-algorithm","tag-binary-search-algorithm-example","tag-binary-search-algorithm-in-c","tag-binary-search-algorithm-in-data-structure","tag-binary-search-c","tag-binary-search-c-program","tag-binary-search-code","tag-binary-search-code-in-c","tag-binary-search-complexity","tag-binary-search-definition","tag-binary-search-example","tag-binary-search-in-c","tag-binary-search-in-c-program","tag-binary-search-in-cpp","tag-binary-search-in-data-structure","tag-binary-search-in-java","tag-binary-search-in-python","tag-binary-search-java","tag-binary-search-java-program","tag-binary-search-program","tag-binary-search-program-in-c","tag-binary-search-program-in-c-using-function","tag-binary-search-program-in-cpp","tag-binary-search-program-in-data-structure","tag-binary-search-program-in-java","tag-binary-search-python","tag-binary-search-recursive-algorithm","tag-binary-search-time-complexity","tag-binary-search-tree","tag-binary-search-tree-algorithm","tag-binary-search-tree-example","tag-binary-search-tree-in-c","tag-binary-search-tree-in-data-structure","tag-binary-search-tree-insertion","tag-binary-search-tree-java","tag-binary-search-tree-program","tag-binary-search-using-recursion","tag-binary-search-using-recursion-in-c","tag-binary-semaphore","tag-binary-sort","tag-binary-sort-in-c","tag-binary-tree","tag-binary-tree-algorithm","tag-binary-tree-example","tag-binary-tree-in-c","tag-binary-tree-insertion","tag-binary-tree-java","tag-binary-tree-traversal","tag-binary-tree-vs-binary-search-tree","tag-bst-data-structure","tag-bst-tree","tag-c-program-for-binary-search","tag-complexity-of-binary-search","tag-complexity-of-binary-search-algorithm","tag-heap-sort","tag-image-search","tag-internet-search-engines","tag-java-binary-search","tag-java-program-for-binary-search","tag-linear-and-binary-search","tag-linear-search-and-binary-search","tag-linear-search-java","tag-merge-sort","tag-meta-search-engine","tag-program-for-binary-search","tag-recursive-binary-search-algorithm","tag-search-algorithms","tag-search-engine-marketing","tag-search-inc","tag-search-search","tag-search-tree","tag-searching-algorithms-in-c","tag-searching-algorithms-in-java","tag-searching-c","tag-seo","tag-the-complexity-of-binary-search-algorithm-is","tag-time-complexity-of-binary-search","tag-web-search-engines","tag-what-is-binary-search","tag-what-is-binary-search-tree"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/24959","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=24959"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/24959\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=24959"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=24959"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=24959"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}