Binary Search

Binary Search Example

by Sandeep Kumar

HTML

<div id="banner-message">
  <div id="divInput">
    <input type="text" id="inpNumber" placeholder="Enter the number" />
  </div>
  <button>Search Number</button>
  <br />
  <span id="searchResult"></span>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

#divInput {
  padding: 5px;
  margin-bottom: 5px;
}

#spanCubeRoot {
  padding: 5px;
  margin-top: 5px;
}

JavaScript

// find elements
var button = $("button")

// handle click and add class
button.on("click", () => {
	let arr = [ 2, 3, 4, 10, 40 ];
  let n = arr.length;
  let x = parseInt($("#inpNumber").val());
  
  let result = binarySearch(arr, 0, n - 1, x);
  
  var text = result == -1
  						? "Element is not present in array"
          		: "Element is present at index " + result;
  
   $("#searchResult").text(text);
})

// JavaScript program to implement recursive Binary Search
 
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
function binarySearch(arr, l, r, x){
    if (r >= l) {
        let mid = l + Math.floor((r - l) / 2);
 
        // If the element is present at the middle
        // itself
        if (arr[mid] == x)
            return mid;
 
        // If element is smaller than mid, then
        // it can only be present in left subarray
        if (arr[mid] > x)
            return binarySearch(arr, l, mid - 1, x);
 
        // Else the element can only be present
        // in right subarray
        return binarySearch(arr, mid + 1, r, x);
    }
 
    // We reach here when element is not
    // present in array
    return -1;
}