{"id":1552,"date":"2023-03-09T15:08:38","date_gmt":"2023-03-09T15:08:38","guid":{"rendered":"https:\/\/www.antpace.com\/blog\/?p=1552"},"modified":"2025-08-25T18:03:34","modified_gmt":"2025-08-25T18:03:34","slug":"binary-search-javascript","status":"publish","type":"post","link":"https:\/\/www.antpace.com\/blog\/binary-search-javascript\/","title":{"rendered":"Binary Search in JavaScript"},"content":{"rendered":"<p>&#8220;Binary search&#8221; is a computer science term used in programming and software engineering. It is a way of determining if a value exists in an ordered data set. It&#8217;s considered a textbook algorithm. <strong>It is useful because it reduces the search space by half on each iteration.<\/strong><\/p>\n<p>Imagine we are asked to search for an integer in an array that is sorted in ascending order. The challenge is to return the target number&#8217;s index.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1553\" src=\"https:\/\/www.antpace.com\/blog\/wp-content\/uploads\/2022\/05\/binary-search.png\" alt=\"binary search\" width=\"782\" height=\"63\" \/><\/p>\n<p>We could use a built in JavaScript function <em>indexOf()<\/em>:<\/p>\n<pre>var search = function(nums, target) {\n    var answer = nums.indexOf(target);\n    console.log(answer);\n    return answer;\n};\nconsole.log(search([-1,0,3,4,5,9,12], 5)); \/\/ returns '4'\n<\/pre>\n<p>But that is an abstraction, which can be slow and expensive. Instead, we should implement our own binary search code.<\/p>\n<h2>Binary Search Implementation<\/h2>\n<p>Binary search starts in the middle of a collection, and checks if that is the requested term. The initial middle position is determined by taking the length of the array and dividing it by two. If the array has an even number of elements, then the &#8216;halfway position&#8217; is considered close enough. I use a JavaScript Math function to round down, making sure I am not left with a decimal floating number:<\/p>\n<pre>cursor =  Math.floor( ((left + right) \/ 2) ); \/\/ about the middle\n<\/pre>\n<p>If the search term is not found, the position (the cursor) is moved. Since the collection is ordered from smallest to largest we know which direction to move the search cursor. If the target is less than the current value, we shift <strong>one<\/strong> to the left. If the target is greater than the current value, we shift <strong>two<\/strong> to the right.<\/p>\n<p>This continues until the target query is found. That sequence is ran inside of a loop. The loop repeats while the left boundary is less than (or equal to) the right. The search cursor&#8217;s index is changed by adjusting the left or right bounds. Once adjusted, the cursor is recalculated on the subsequent iteration.<\/p>\n<pre>var search = function(nums, target) {\n    var left = 0; \/\/ first element, initial left boundary\n    var right = nums.length;\n    right = right - 1; \/\/ last element, initial right boundary\n    var cursor = 0;\n    while(left &lt;= right){\n        cursor =  Math.floor( ((left + right) \/ 2) ); \/\/ about the middle to start\n        console.log(cursor + \": \" + nums[cursor]);\n        if(nums[cursor] === target){\n            return cursor; \/\/ query found!\n        }\n        if(target &lt; nums[cursor]){\n            right = cursor - 1; \/\/ move cursor to the left by one\n            console.log(\"cursor moved to the left  by one\")\n        }else{\n            left = cursor + 1; \/\/ move cursor to the right by two\n            console.log(\"cursor moved to the right by two\")\n        }\n    }\n    return \"false\"; \/\/ not found\n};\nconsole.log(search([-1,0,1,2,3,4,5,6,7,8,9,10,11,12], 10));\n\n<\/pre>\n<p>The above code starts to search in the central location, <em>nums[6] == 5<\/em>. Look at the output below to see how the cursor moves until it finds the target value of 10 (at a zero-based index of 11):<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1554\" src=\"https:\/\/www.antpace.com\/blog\/wp-content\/uploads\/2022\/05\/binary-seach-output.png\" alt=\"binary search output\" width=\"923\" height=\"209\" \/><\/p>\n<p>This algorithm has an <em>O(log n)<\/em> runtime complexity. That Big-O notation describes how it would scale as the input increases. Imagine an array with thousands of elements. <em>O(log<\/em> n) means that the time to execute this code will increase linearly only as the number of input items increase <em>exponentially<\/em>. That means our code is performant and efficient.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1786\" src=\"https:\/\/www.antpace.com\/blog\/wp-content\/uploads\/2022\/11\/joke-about-binary-search.png\" alt=\"Why did the computer scientist use binary search to find his lost pencil? Because he wanted to reduce the search space by half every time he checked a desk drawer!\" width=\"642\" height=\"142\" \/><\/p>\n<h2>Square root algorithm using binary search<\/h2>\n<p>Another implementation example of using binary search in a JavaScript function is to calculate the square root of a number. Now, of course, Javascript has a built in <code>Math.sqrt()<\/code> function that is highly performant compared to any custom code we will write. But, it is a good exercise to think about how this works.<\/p>\n<p>The square root of a number is a value that, when multiplied by itself, gives the original number. To solve for it when given an input, we are going to take a guess at what the answer (square root) is, starting with itself divided by two (giving us the midpoint between it and zero). We multiply that midpoint by itself to check our guess. It will only be correct on the first iteration if the input is the number four (four divided by two is two; two times two is four). Otherwise, we will move the cursor (halving the search range) to either the left or the right, depending on if the square of our guess is larger or smaller than the original input.<\/p>\n<p>The concept of &#8220;moving the cursor&#8221; helps to visualize how the binary search algorithm zeroes in on the square root by iteratively narrowing down the search range based on the comparison of the square of the midpoint to the target number.<\/p>\n<p>I accounted for two special cases in my code. For negative numbers we return false because negative numbers have imaginary square roots. For numbers smaller than one we set the range&#8217;s end to one because the square root of a fraction is larger than the fraction itself. Additionally, I set a precision threshold (0.0000000001), because some numbers have square roots that are irrational.<\/p>\n<pre>function binarySearchSquareRoot(n, precision = 1e-10) {\n    if (n &lt; 0) {\n        throw new Error('Input must be a non-negative number');\n    }\n\n    let start = 0;\n    let end = n;\n\n    \/\/ If the number is less than 1, set end to 1 to handle fractions\n    if (n &lt; 1) {\n        end = 1;\n    }\n\n    while (end - start &gt; precision) {\n        const mid = (start + end) \/ 2;\n        const midSquared = mid * mid;\n\n        if (midSquared === n) {\n            return mid;  \/\/ Found exact square root\n        } else if (midSquared &lt; n) {\n            start = mid;\n        } else {\n            end = mid;\n        }\n    }\n\n    return (start + end) \/ 2;  \/\/ Return approximate square root\n}\n\n\/\/ Usage:\nconst number = 25;\nconst squareRoot = binarySearchSquareRoot(number);\nconsole.log(`The square root of ${number} is approximately ${squareRoot}`);\n<\/pre>\n<p>Alternatively, the Babylonian algorithm can be\u00a0 implemented to solve for square roots.<\/p>\n<h4>Additional References<\/h4>\n<p><a href=\"https:\/\/delboy1978uk.wordpress.com\/2018\/02\/06\/binary-search-trees-in-php\/\" target=\"_blank\" rel=\"noopener\">https:\/\/delboy1978uk.wordpress.com\/2018\/02\/06\/binary-search-trees-in-php\/<\/a><br \/>\n<a href=\"https:\/\/research.google\/blog\/extra-extra-read-all-about-it-nearly-all-binary-searches-and-mergesorts-are-broken\/\" target=\"_blank\" rel=\"noopener\">https:\/\/research.google\/blog\/extra-extra-read-all-about-it-nearly-all-binary-searches-and-mergesorts-are-broken\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;Binary search&#8221; is a computer science term used in programming and software engineering. It is a way of determining if a value exists in an ordered data set. It&#8217;s considered a textbook algorithm. It is useful because it reduces the search space by half on each iteration. Imagine we are asked to search for an &hellip; <\/p>\n<p class=\"link-more\"><a href=\"https:\/\/www.antpace.com\/blog\/binary-search-javascript\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Binary Search in JavaScript&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":3263,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5],"tags":[7,16,28,71,99,120],"class_list":["post-1552","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-development","tag-algorithms","tag-binary-search","tag-computer-science","tag-javascript","tag-programming","tag-software-engineer"],"_links":{"self":[{"href":"https:\/\/www.antpace.com\/blog\/wp-json\/wp\/v2\/posts\/1552","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.antpace.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.antpace.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.antpace.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.antpace.com\/blog\/wp-json\/wp\/v2\/comments?post=1552"}],"version-history":[{"count":1,"href":"https:\/\/www.antpace.com\/blog\/wp-json\/wp\/v2\/posts\/1552\/revisions"}],"predecessor-version":[{"id":3264,"href":"https:\/\/www.antpace.com\/blog\/wp-json\/wp\/v2\/posts\/1552\/revisions\/3264"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.antpace.com\/blog\/wp-json\/wp\/v2\/media\/3263"}],"wp:attachment":[{"href":"https:\/\/www.antpace.com\/blog\/wp-json\/wp\/v2\/media?parent=1552"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.antpace.com\/blog\/wp-json\/wp\/v2\/categories?post=1552"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.antpace.com\/blog\/wp-json\/wp\/v2\/tags?post=1552"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}