MCPcopy Create free account
hub / github.com/Vishal-raj-1/Awesome-JavaScript-Projects / BinarySearch

Function BinarySearch

assets/js/binarysearch.js:47–109  ·  view source on GitHub ↗
(delay = 300)

Source from the content-addressed store, hash-verified

45
46// Asynchronous BinarySearch function
47async function BinarySearch(delay = 300) {
48var blocks = document.querySelectorAll(".block");
49var output = document.getElementById("text");
50
51//Extracting the value of the element to be searched
52var num = document.getElementById("fname").value;
53
54//Colouring all the blocks voilet
55for (var i = 0; i < blocks.length; i += 1) {
56 blocks[i].style.backgroundColor = "#00ccff";
57}
58
59output.innerText = "";
60
61// BinarySearch Algorithm
62
63var start = 0;
64var end = 19;
65var flag = 0;
66while (start <= end) {
67 //Midddle index
68 var mid = Math.floor((start + end) / 2);
69 blocks[mid].style.backgroundColor = "#FF4949";
70
71 //Value at mid index
72 var value = Number(blocks[mid].childNodes[0].innerHTML);
73
74 // To wait for .1 sec
75 await new Promise((resolve) =>
76 setTimeout(() => {
77 resolve();
78 }, delay)
79 );
80
81 //Current element is equal to the element
82 //entered by the user
83 if (value == num) {
84 output.innerText = "Element Found";
85 blocks[mid].style.backgroundColor = "#13CE66";
86 flag = 1;
87 break;
88 }
89 //Current element is greater than the element
90 //entered by the user
91 if (value > num) {
92 end = mid - 1;
93 blocks[mid].style.backgroundColor = "#00ccff";
94 } else {
95 start = mid + 1;
96 blocks[mid].style.backgroundColor = "#00ccff";
97 }
98}
99if (flag === 0) {
100 output.innerText = "Element Not Found";
101}
102 // To enable the button "Generate New Array" after final(sorted)
103 document.getElementById("Button1").disabled = false;
104 document.getElementById("Button1").style.backgroundColor = "#6f459e";

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected