Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
Linear Search Visualization using JavaScript
Next article icon

Ternary Search Visualization using JavaScript

Last Updated : 24 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

GUI(Graphical User Interface) helps better in understanding than programs. In this article, we will visualize Ternary Search using JavaScript. We will see how the elements are being traversed in Ternary Search until the given element is found. We will also visualize the time complexity of Ternary Search.

Refer:

  • Ternary Search
  • Asynchronous Function in JavaScript

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 TernarySearch() function.
Before Searching
After Searching

Below is the program to visualize the Ternary Search algorithm.

index.html
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8" />     <meta name="viewport" content=         "width=device-width, initial-scale=1.0" />     <link rel="stylesheet" href="style.css" /> </head>  <body>     <br />     <p class="header">Ternary Search</p>       <div id="array"></div>     <br /><br />      <div style="text-align: center">         <label for="fname">         Number to be Searched:       </label>         <input type="text" id="fname" name="fname" />         <br /><br />         <button id="btn" onclick="TernarySearch()">         Search       </button>         <br />         <br />         <div id="text"></div>     </div>      <script src="script.js"></script> </body>  </html> 

style.css: The following is the content for “style.css” used in the above file.

style.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 all ease; }  .block_id {     position: absolute;     color: black;     margin-top: -20px;     width: 100%;     text-align: center; } 

script.js: The following is the content for “script.js” file used in the above HTML code.

script.js
var container = document.getElementById("array");  // Function to generate the array of blocks function generatearray() {      // Creating an array     var arr = [];      // Filling array with random values     for (var i = 0; i < 20; i++) {          // Return a value from 1 to 100 (both inclusive)         var val = Number(Math.ceil(Math.random() * 100));         arr.push(val);     }      // Sorting Array in ascending order     arr.sort(function(a, b) {         return a - b;     });      for (var i = 0; i < 20; i++) {         var value = arr[i];          // Creating element div         var array_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         var array_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 TernarySearch function async function TernarySearch(delay = 700) {     var blocks = document.querySelectorAll(".block");     var output = document.getElementById("text");      // Extracting the value entered by the user     var num = document.getElementById("fname").value;      // Colouring all the blocks violet     for (var i = 0; i < blocks.length; i += 1) {         blocks[i].style.backgroundColor = "#6b5b95";     }      output.innerText = "";      // TernarySearch Algorithm     var start = 0;     var end = 19;     var flag = 0;     while (start <= end) {         var mid1 = Math.floor(start + (end - start) / 3);         var mid2 = Math.floor(end - (end - start) / 3);          // Extracting values of mid1 and mid2 blocks         var value1 = Number(blocks[mid1].childNodes[0].innerHTML);         var value2 = Number(blocks[mid2].childNodes[0].innerHTML);          // Changing color to red         blocks[mid1].style.backgroundColor = "#FF4949";         blocks[mid2].style.backgroundColor = "#FF4949";          // To wait for .1 sec         await new Promise((resolve) =>             setTimeout(() => {                 resolve();             }, delay)         );          // Number entered by the user equals to         // element at mid1         if (value1 == num) {             output.innerText = "Element Found";             blocks[mid1].style.backgroundColor = "#13CE66";             flag = 1;             break;         }          // Number entered by the user equals to         // element at mid2         if (value2 == num) {             output.innerText = "Element Found";             blocks[mid2].style.backgroundColor = "#13CE66";             flag = 1;             break;         }          if (num < value1) {             end = mid1 - 1;         } else if (num > value2) {             start = mid2 + 1;         } else {             start = mid1 + 1;             end = mid2 - 1;         }     }      if (flag === 0) {         output.innerText = "Element Not Found";     } }  // Calling generatearray function generatearray(); 

Output:


Next Article
Linear Search Visualization using JavaScript

T

tk315
Improve
Article Tags :
  • Searching
  • Technical Scripter
  • JavaScript
  • Web Technologies
  • HTML
  • CSS
  • DSA
  • Technical Scripter 2020
  • HTML-Questions
  • CSS-Questions
  • JavaScript-Questions
Practice Tags :
  • Searching

Similar Reads

  • Linear Search Visualization using JavaScript
    GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Linear Search using JavaScript. We will see how the elements are being traversed in Linear Search until the given element is found. We will also visualize the time complexity of Linear Se
    3 min read
  • Binary Search Visualization using JavaScript
    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 Searc
    4 min read
  • Heap Sort Visualization using JavaScript
    GUI(Graphical User Interface) helps in better understanding than programs. In this article, we will visualize Heap Sort using JavaScript. We will see how the array is first converted into Maxheap and then how we get the final sorted array. We will also visualize the time complexity of Heap Sort. Ref
    4 min read
  • Brick Sort Visualization using JavaScript
    This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd-indexed elements, and in the even phase, we perform a bubble sort on even-indexed elements. To know more about it. Please refer to Brick Sor
    6 min read
  • Bucket Sort Visualization Using Javascript
    GUI(Graphical User Interface) helps in better understanding than programs. In this article, we will visualize Bucket Sort using JavaScript. We will see how the elements are stored in Buckets and then how Buckets get traversed to get the final sorted array. We will also visualize the time complexity
    7 min read
  • Counting Sort Visualization using JavaScript
    GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Counting Sort using JavaScript. We will see how the frequencies of elements are stored and how we get the final sorted array. We will also visualize the time complexity of Counting Sort.
    4 min read
  • Insertion Sort Visualization using JavaScript
    Insertion sort is a simple sorting algorithm in which values from the unsorted part are picked and placed at the correct position in the sorted part. In order to know more about it. Please refer Insertion Sort. An algorithm like Insertion Sort can be easily understood by visualizing instead of long
    5 min read
  • Merge Sort Visualization in JavaScript
    GUI(Graphical User Interface) helps users with better understanding programs. In this article, we will visualize Merge Sort using JavaScript. We will see how the arrays are divided and merged after sorting to get the final sorted array.  Refer: Merge SortCanvas in HTMLAsynchronous Function in JavaSc
    4 min read
  • Shell Sort Visualizer using JavaScript
    Shell Sort is mainly a variation of Insertion Sort. The idea of shell sort is to allow the exchange of far items. In order to know more about it. Please refer to Shell Sort. An algorithm like Shell Sort can be easily understood by visualizing instead of long codes. In this article, Shell Sort Visual
    5 min read
  • Comb Sort Visualizer using JavaScript
    Comb Sort is mainly an improvement over Bubble Sort. Comb Sort improves on Bubble Sort by using a gap of the size of more than 1. In order to know more about it. Please refer to Comb Sort. An algorithm like Comb Sort can be easily understood by visualizing instead of long codes. In this article, Com
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences