# How to visualize ternary search using JavaScript ?

JavascriptProgramming ScriptsWeb DevelopmentFront End Technology

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

In this tutorial we will create ternary search visualization using JavaScript,

As you know code but think if you’ll see your code doing work in front of your eyes in GUI representation that how amazing it would be. So here we will be working on creation of visualization part of the ternary search.

Before let’s first get to know about what ternary search is?

## Ternary Search in JavaScript

Ternary Search is a divide & conquer algorithm similar to binary search it divides the array into parts of 3 and determine which side element would exist unlike in binary search we divide the array into two parts then we determine which side element would be.

So, in ternary search there would be 2 mid values.

Middle1= left + ( right-left ) / 3
Middle2= right- ( right-left ) / 3


To perform ternary search on the array we have to follow some steps.

• We calculate middle1 and compare the given key with middle1 value if it’s equal then we return the middle1 as we found the key.

• In case we didn’t find the key element then we will calculate middle2 and compare with key2 if it’s equal to middle2 value then return the middle2 we found the key.

• If above case failed, then we check if key is lesser then the middle1 value if true then we will start checking in first part of array. Else in case key is greater than the middle2 value then we will search in the third part of the array. Else we will check in the second part which is middle part of the array.

### Example

Arr: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
key=6
Left=0, right=10, middle1=3, middle2=7
//using above explained formula


As key>arr[middle1] and key<arr[middle2] means we will have to search in the middle part,

Left=4, right=6, middle1=4, middle2=6 here also key>arr[middle1] and key<arr[middle2]

So here also we will search in middle part of our array.

Left=5, right=5, middle1=5, middle2=5


And out key=arr[middle1] so we’ve found our key=6 at index 5

So, this is how it will work, now let’s implement it in code.

## Approach

We will follow the below steps, to visualize ternary search in JavaScript −

• To perform ternary search, we will generate our array from Random method from Math library.

• We will use asynchronous function which is setTimeout to make our algorithm working slow as you know machine does work really fast and, in this manner, visualising the work is really very tough.

### Example

Let’s add our design to the browser screen.

<html>
<title>Ternary search visualization using JavaScript.</title>
<style>
#listItem {
position: relative;
margin-top: 64px;
background-color: white;
height: 305px;
width: 568px;
margin: auto;
}

.box {
width: 20px;
background-color: #391306;
position: absolute;
bottom: 0px;
transition: 0.2s all ease;
margin:auto;
}

.box_nm {
margin-top: -23px;
width: 100%;
text-align: center;
position: absolute;
color: black;
}
</style>
<body>
<br/>
<h2>Ternary Search visualization</h2>
<div id="listItem"></div>
<br/><br />
<div style="text-align: center">
<input id="btn1" type="button" value="DisplayArray" onClick="arrayDisplay()" style="background-color: skyblue; cursor: pointer;"/>
<h3>Enter key to search?</h3>

<input type="text" id="valueToSearch" name="valueToSearch"/>

<br/><br />

<input id="btn2" type="button" value="Search" onclick="Ternary_Search()" style="background-color: skyblue; cursor: pointer;">

<br/><br/>
<div id="writeHere"></div>
</div>
</body>
</html>


When the DiaplayArray button will be clicked then arrayDisplay() method will be called and it will show the container containing random element and box of size as array container number, when the Search button will be clicked then it will call the function Ternary_serach() and we will perform the ternary search operation in that function as we’ve discussed the approach how it will be working, Now let’s add our JavaScript function code to the html code.

### Example

<html>
<title>Ternary search visualization using JavaScript.</title>
<style>
#listItem {
position: relative;
margin-top: 64px;
background-color: white;
height: 305px;
width: 568px;
margin: auto;
}

.box {
width: 20px;
background-color: #391306;
position: absolute;
bottom: 0px;
transition: 0.2s all ease;
margin:auto;
}

.box_nm {
margin-top: -23px;
width: 100%;
text-align: center;
position: absolute;
color: black;
}
</style>
<body>
<br/>
<h2>Ternary Search visualization</h2>

<div id="listItem"></div>
<br/><br />

<div style="text-align: center">
<input id="btn1" type="button" value="DisplayArray" onClick="arrayDisplay()" style="background-color: skyblue; cursor: pointer;"/>
<h3>Enter key to search?</h3>
<input type="text" id="valueToSearch" name="valueToSearch"/>

<br/><br />

<input id="btn2" type="button" value="Search" onclick="Ternary_Search()" style="background-color: skyblue; cursor: pointer;">

<br/><br/>

<div id="writeHere"></div>
</div>
<script>
const arrayDisplay=()=>{
var ItemBox = document.getElementById("listItem");
const list = [];
for (var i = 0; i < 17; i++) {
list.push(Number(Math.ceil(Math.random() * 80)));
}
list.sort((ele1, ele2)=>{return ele1 - ele2;});
for (var i = 0; i < 17; i++) {
var currItem = list[i], element = document.createElement("div");
element.style.height = ${currItem * 2}px; element.style.transform = translate(${i * 30}px);

var eleUsingLabel = document.createElement("label");
eleUsingLabel.textContent = currItem;
element.appendChild(eleUsingLabel);
ItemBox.appendChild(element);
}
}
const Ternary_Search=async()=>{
var box = document.querySelectorAll(".box");
var DisplayResult = document.getElementById("writeHere");
DisplayResult.textContent = "";
var valueToSearch = document.getElementById("valueToSearch").value;
box.forEach(boxi=>{
boxi.style.backgroundColor="#391306"
})
var left = 0, right=16, notFound=0;
while (left <= right) {
var middle1 = Math.floor(left + (right - left) / 3);
var middle2 = Math.floor(right - (right - left) / 3);
var value1 = Number(box[middle1].childNodes[0].innerHTML);
var value2 = Number(box[middle2].childNodes[0].innerHTML);
await new Promise((resolve) =>setTimeout(() => {resolve();}, 1000));

if (valueToSearch == value1) {
DisplayResult.textContent = "Element Found at position: "+(middle1+1);
box[middle1].style.backgroundColor = "#F51720";
notFound = 1;
break;
}

if (valueToSearch == value2) {
DisplayResult.textContent = "Element Found at position: "+(middle2+1);
box[middle2].style.backgroundColor = "#F51720";
notFound = 1;
break;
}

if (valueToSearch < value1)
right = middle1 - 1;
else if (valueToSearch > value2)
left = middle2 + 1;
else
left = middle1 + 1, right = middle2 - 1;
}
if (notFound === 0) {
}
}
</script>
</body>
</html>


In the arrayDisplay method we created an array with some random numbers in range from 1 to 80 then we applied the sort of function as you know ternary search will only work on sorted array.

We add the blocks to represent the array elements with its height equal to the array value with text label.

We will append all the boxes inside the parent container.

In the Ternary_Search method we will first add colors to all the boxes and fetch the entered value which will be searched.

Now we will apply ternary search algorithm and we will apply async await as we have to show the animation in slow because computer does computer too much fast so showing it in slow manner, we will apply await.

Now we will check if we’ve found the value then we will print yes with it’s index name.

So, you got to know about idea of creating visualization of ternary search using JavaScript.

Updated on 11-Oct-2022 09:02:07