JavaScript Array Binary Search

This page discusses - JavaScript Array Binary Search

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:

<html>
<head>
<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;
else
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);
}
</script>
</head>
<body onload="search()"/>
</html>

Output will be displayed as:

Download Source Code