How to Visualize Heap Sort using JavaScript?

JavascriptProgramming ScriptsWeb DevelopmentFront End Technology

In this tutorial, we will create Heap sort visualization using JavaScript,

Learning through only code doesn’t seem interesting but think if you’ll see your code doing work in front of your eyes in GUI representation how amazing it would be. So here we will be working on the creation of the visualization part of the Heap sort.

Before let’s first get to know about what Heap sort & some of its terminology.

Quick Sort in JavaScript

Heap sort is an in-place sorting algorithm based on data structure.

Heap − heap is an ordered complete binary tree data structure.

Max heap − Value of parent will always be greater than the child value.

Min heap − Value of parent will always be lower than the child value.

Heapify − Creating max heap using unsorted array values but it assumes that part of array value is already sorted.

Relation between tree and array indexes

As you got to know about heap which is a complete binary tree so when we represent these tree elements in the array format than for index i element in the array left child will be at index (2i+1) value and right child will be at index (2i+2), if we talk about parent of index i value then it will be at lower_bound of index (i-1)/2.

Example

For array 3 15 9 4 6 11 Left child of value 15(index 1) will be at index (2*1+1)= 3 which is 4. Right child of value 15(index 1) will be at index (2*1+2)= 4 which is 6.

Procedure to perform heap sort

Step 1 − Create max heap.

Step 2 − Remove largest item.

Step 3 − Place item in sorted partition

For more details visit Heap Sort

Add our HTML & CSS design to the browser screen.

Example

We will create our design and add html elements to visualize the algorithm.

<html> <head> <title>Heap Sort visualization using JavaScript.</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> #listItem { position: relative; margin-top: 64px; background-color: lightblue; height: 305px; width: 590px; margin: auto; } .box { width: 20px; background-color: #050A30; 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; } #btn1{ color: red; font-size: 20px; width: 170px; height: 50px; cursor: pointer; } #btn2{ color: blue; font-size: 20px; width: 160px; height: 50px; cursor: pointer; } </style> </head> <body> <br/> <h2 style="font-family: cursive; text-align:center">Heap Sort Visualization</h2> <div id="listItem"></div> <br/><br /> <div style="text-align: center"> <button id="btn1" onclick="arrayDisplay()">Display Array <i class="fa fa-desktop"></i></button> <button id="btn2" onclick="HSort()">Sort Array <i class="fa fa-sort"></i></button> <br/><br/> <h2 id="writeHere"></h2> </div> </body> </html>

When the Display Array button will be clicked then arrayDisplay() method will be called and it will show the container containing a random element and box of size as array container number when the Sort button will be clicked then it will call the function HSort() and it will perform the heap sort operation by calling HeapSort() function in that function as we’ve discussed the approach above how it will be working.

Approach

Let’s understand the program and functions more using steps −

Step 1 − Created an array to store initial random generated values.

Step 2 − Display the array randomly generated values by creating colourful blocks with height as array value.

Step 3 − Call Heap Sort function to perform algorithm operations on the array.

Step 4 − Created box with updated arrays value which have been changed after heapify.

Step 5 − Add timeout to set the delay between the creation of every bar to visualize heap sort slowly.

Example

Full Heap sort program:

<html> <head> <title>Heap Sort visualization using JavaScript.</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> #listItem { position: relative; margin-top: 64px; background-color: lightblue; height: 305px; width: 590px; margin: auto; } .ElementBox { width: 20px; background-color: #050A30; 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; } #btn1{ color: red; font-size: 20px; width: 170px; height: 50px; cursor: pointer; } #btn2{ color: blue; font-size: 20px; width: 160px; height: 50px; cursor: pointer; } </style> </head> <body> <br/> <h2 style="font-family: cursive; text-align:center">Heap Sort Visualization</h2> <div id="listItem"></div> <br/><br /> <div style="text-align: center"> <button id="btn1" onclick="arrayDisplay()">Display Array <i class="fa fa-desktop"></i></button> <button id="btn2" onclick="HSort()">Sort Array <i class="fa fa-sort"></i></button> <br/><br/> <h2 id="writeHere"></h2> </div> <script> const list = []; // display initial array with random values function arrayDisplay(){ let ItemBox = document.getElementById("listItem"); for (let i = 0; i < 20; i++) { list.push(Number(Math.ceil(Math.random() * 80))); } for (let i = 0; i < 20; i++) { let currItem = list[i], element = document.createElement("div"); element.classList.add("ElementBox"); element.style.height = `${currItem * 2}px`; element.style.transform = `translate(${i * 30}px)`; let eleUsingLabel = document.createElement("label"); eleUsingLabel.classList.add("box_nm"); eleUsingLabel.textContent = currItem; eleUsingLabel.setAttribute("style", "font-weight: bold;") element.appendChild(eleUsingLabel); ItemBox.appendChild(element); } } function applyDesign(ElementBox, index){ } function Createtimeout(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function heapify(num, index){ var ElementBox = document.querySelectorAll(".ElementBox"); let largest = index; let l_index = 2 * index + 1; let r_index = 2 * index + 2; if (l_index <num && Number(ElementBox[l_index].childNodes[0].innerHTML) >Number(ElementBox[largest].childNodes[0].innerHTML)) largest = l_index; if (r_index < num && Number(ElementBox[r_index].childNodes[0].innerHTML) >Number(ElementBox[largest].childNodes[0].innerHTML)) largest = r_index; if (largest != index) { var ElementBox_height_temp = ElementBox[index].style.height; var ElementBox_label_value = ElementBox[index].childNodes[0].innerText; ElementBox[index].style.height = ElementBox[largest].style.height; ElementBox[largest].style.height = ElementBox_height_temp; ElementBox[index].childNodes[0].innerText =ElementBox[largest].childNodes[0].innerText; ElementBox[largest].childNodes[0].innerText = ElementBox_label_value; await Createtimeout(300); await heapify(num, largest); } } // Heap sort function const HeapSort=async()=>{ let ElementBox = document.querySelectorAll(".ElementBox"); var num=20; //building max heap for(let index=num/2-1;index>=0;index--){ await heapify(num, index); } //heap sort for(let index=num-1; index>=0; index--){ // swap element and bring current root to end var ElementBox_height_temp = ElementBox[index].style.height; var ElementBox_label_value = ElementBox[index].childNodes[0].innerText; ElementBox[index].style.height = ElementBox[0].style.height; ElementBox[0].style.height = ElementBox_height_temp; ElementBox[index].childNodes[0].innerText =ElementBox[0].childNodes[0].innerText; ElementBox[0].childNodes[0].innerText = ElementBox_label_value; await Createtimeout(300) //heapify the elements to get heighest value node at the root node await heapify(index, 0); } } const HSort=async()=>{ await HeapSort() ; document.getElementById("writeHere").innerHTML="HeapSort applied Successfully." } </script> </body> </html>

So, we got to know about the heap sort visualization program.

raja
Updated on 11-Oct-2022 09:32:51

Advertisements