Share on Google+Share on Google+

JavaScript Array Binary Search

This page discusses - JavaScript Array Binary Search

JavaScript Array Binary Search


The JavaScript Binary Search becomes very useful in case of large Arrays.  The Binary Search algorithm is used to  handle the array data. The algorithm allows you to search a particular element from the array. In the given example, we have create an instance of Array and added few elements into it and search the 'Innova' car from the Array. On calling the function search(), the index number of that element have been displayed on the browser.

Here is the code:

<script type="text/javaScript">
arr = new Array()
arr[0] = 'Nano';
arr[1] = 'Indica';
arr[2] = 'BMW';
arr[3] = 'Innova';
arr[4] = 'Toyoto';
arr[5] = 'Alto';
arr[6] = 'Maruti';
arr[7] = 'Spark';
arr[8] = 'Chevrolet spark';

function binarySearch(arr, key){
var left = 0;
var right = arr.length - 1;
while (left <= right){
var mid = parseInt((left + right)/2);
if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
left = mid + 1;
right = mid - 1;
return arr.length;
function search(){
var element= binarySearch(arr,'Innova');
document.write("<h2>Binary Search Example</h2>");
document.write("<b>The element you are searching is at
   the index number: </b>"+ element);
<body onload="search()"/>

Output will be displayed as:

Download Source Code


Posted on: April 17, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: JavaScript Array Binary Search  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
David F Mayer
March 28, 2012
Binary Search

Will work ONLY if array is sorted prior to being searched.
May 15, 2013

array must be sorted, shows you don't understand a binary search,...