GUI(Graphical User Interface) helps in better understanding than programs. In this article, we will visualize Binary Search using JavaScript. We will see how the elements are being traversed in Binary Search until the given element is found. We will also visualize the time complexity of Binary Search.
Reference:
Approach:
- First, we will generate a random array using Math.random() function and then sort it using sort() function.
- Different color is used to indicate which element is being traversed at current time.
- Since the algorithm performs the operation very fast, the setTimeout() function has been used to slow down the process.
- New array can be generated by pressing the “Ctrl+R” key.
- The searching is performed using BinarySearch() function.
Example:
 
Before Searching
 
After Searching
Below is the program to visualize the Binary Search algorithm.
Filename: index.html
HTML
| <!DOCTYPE html><htmllang="en">  <head>    <metacharset="UTF-8"/>    <metaname="viewport"          content="width=device-width, initial-scale=1.0"/>    <linkrel="stylesheet"href="style.css"/>  </head>  <body>    <br/>    <pclass="header">Binary Search</p>    <divid="array"></div>    <br/><br/>    <divstyle="text-align: center">      <labelfor="fname">        Number to be Searched:      </label>      <inputtype="text"id="fname"             name="fname"/>      <br/><br/>      <buttonid="btn"              onclick="BinarySearch()">Search</button>      <br/>      <br/>      <divid="text"></div>    </div>    <scriptsrc="script.js"></script>  </body></html> | 
Filename: style.css
CSS
| * {  margin: 0px;  padding: 0px;  box-sizing: border-box;}.header {  font-size: 35px;  text-align: center;}#array {  background-color: white;  height: 305px;  width: 598px;  margin: auto;  position: relative;  margin-top: 64px;}.block{  width: 28px;  background-color: #6b5b95;  position: absolute;  bottom: 0px;  transition: 0.2s allease;}.block_id {  position: absolute;  color: black;  margin-top: -20px;  width: 100%;  text-align: center;} | 
Filename: script.js
Javascript
| varcontainer = document.getElementById("array");// Function to generate the array of blocksfunctiongeneratearray() {  // Creating an array  vararr = [];  // Filling array with random values  for(vari = 0; i < 20; i++) {    // Return a value from 1 to 100 (both inclusive)    varval = Number(Math.ceil(Math.random() * 100));    arr.push(val);  }  // Sorting Array in ascending order  arr.sort(function(a, b) {    returna - b;  });  for(vari = 0; i < 20; i++) {    varvalue = arr[i];    // Creating element div    vararray_ele = document.createElement("div");    // Adding class 'block' to div    array_ele.classList.add("block");    // Adding style to div    array_ele.style.height = `${value * 3}px`;    array_ele.style.transform = `translate(${i * 30}px)`;    // Creating label element for displaying    // size of particular block    vararray_ele_label = document.createElement("label");    array_ele_label.classList.add("block_id");    array_ele_label.innerText = value;    // Appending created elements to index.html    array_ele.appendChild(array_ele_label);    container.appendChild(array_ele);  }}// Asynchronous BinarySearch functionasync functionBinarySearch(delay = 300) {  varblocks = document.querySelectorAll(".block");  varoutput = document.getElementById("text");  //Extracting the value of the element to be searched  varnum = document.getElementById("fname").value;  //Colouring all the blocks violet  for(vari = 0; i < blocks.length; i += 1) {    blocks[i].style.backgroundColor = "#6b5b95";  }  output.innerText = "";  // BinarySearch Algorithm  varstart = 0;  varend = 19;  varflag = 0;  while(start <= end) {    //Middle index    varmid = Math.floor((start + end) / 2);    blocks[mid].style.backgroundColor = "#FF4949";    //Value at mid index    varvalue = Number(blocks[mid].childNodes[0].innerHTML);    // To wait for .1 sec    await newPromise((resolve) =>      setTimeout(() => {        resolve();      }, delay)    );    //Current element is equal to the element    //entered by the user    if(value == num) {      output.innerText = "Element Found";      blocks[mid].style.backgroundColor = "#13CE66";      flag = 1;      break;    }    //Current element is greater than the element    //entered by the user    if(value > num) {      end = mid - 1;      blocks[mid].style.backgroundColor = "#6b5b95";    } else{      start = mid + 1;      blocks[mid].style.backgroundColor = "#6b5b95";    }  }  if(flag === 0) {    output.innerText = "Element Not Found";  }}// Calling generatearray functiongeneratearray(); | 
Output:
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







