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

Function TernarySearch

assets/js/ternarysearch.js:48–123  ·  view source on GitHub ↗
(delay = 700)

Source from the content-addressed store, hash-verified

46
47// Asynchronous TernarySearch function
48async function TernarySearch(delay = 700) {
49 var blocks = document.querySelectorAll(".block");
50 var output = document.getElementById("text");
51
52 // Extracting the value entered by the user
53 var num = document.getElementById("fname").value;
54
55 // Colouring all the blocks voilet
56 for (var i = 0; i < blocks.length; i += 1) {
57 blocks[i].style.backgroundColor = "#00ccff";
58 }
59
60 output.innerText = "";
61
62 // TernarySearch Algorithum
63 var start = 0;
64 var end = 19;
65 var flag = 0;
66 while (start <= end) {
67 var mid1 = Math.floor(start + (end - start) / 3);
68 var mid2 = Math.floor(end - (end - start) / 3);
69
70 // Extracting values of mid1 and mid2 blocks
71 var value1 = Number(blocks[mid1].childNodes[0].innerHTML);
72 var value2 = Number(blocks[mid2].childNodes[0].innerHTML);
73
74 // Changing color to red
75 blocks[mid1].style.backgroundColor = "#FF4949";
76 blocks[mid2].style.backgroundColor = "#FF4949";
77
78 // To wait for .1 sec
79 await new Promise((resolve) =>
80 setTimeout(() => {
81 resolve();
82 }, delay)
83 );
84
85 // Number entered by the user equals to
86 // element at mid1
87 if (value1 == num) {
88 output.innerText = "Element Found";
89 blocks[mid1].style.backgroundColor = "#13CE66";
90 flag = 1;
91 break;
92 }
93
94 // Number entered by the user equals to
95 // element at mid2
96 if (value2 == num) {
97 output.innerText = "Element Found";
98 blocks[mid2].style.backgroundColor = "#13CE66";
99 flag = 1;
100 break;
101 }
102
103 if (num < value1) {
104 end = mid1 - 1;
105 } else if (num > value2) {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected