Heap Sort Visualization using JavaScript Last Updated : 30 May, 2023 Comments Improve Suggest changes Like Article Like Report 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. Refer: Heap SortAsynchronous Function in JavaScript Approach: First, we will generate a random array using Math.random() function.Different colors are used to indicate which elements are being compared, sorted, and unsorted.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 sorting is performed using HeapSort() function using Heapify() function. Example: In this example, we will see the visualization of Heap Sort by using the above approach. Before SortingAfter Sorting Below is the program to visualize the Heap Sort algorithm. index.html HTML <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css" /> </head> <body> <br /> <p class="header">Heap Sort</p> <div id="array"></div> <div id="count"></div> <script src="script.js"></script> </body> </html> style.css: The following is the content for “style.css” used in the above file. CSS * { margin: 0px; padding: 0px; box-sizing: border-box; } .header { font-size: 20px; text-align: center; } #array { background-color: white; height: 270px; 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; } .block_id2 { position: absolute; color: black; margin-top: 22px; width: 100%; text-align: center; } .block2 { width: 28px; background-color: darkgray; position: absolute; transition: 0.2s all ease; } .block_id3 { position: absolute; color: black; margin-top: 1px; width: 100%; text-align: center; } #count { height: 20px; width: 598px; margin: auto; } script.js: The following is the content for “script.js” file used in the above HTML code. JavaScript let container = document.getElementById("array"); // Function to generate the array of blocks function generatearray() { for (let i = 0; i < 20; i++) { // Return a value from 1 to 100 (both inclusive) let value = Math.ceil(Math.random() * 100); // Creating element div let 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 let 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); } } // Function to generate the indexes let count_container = document.getElementById("count"); function generate_idx() { for (let i = 0; i < 20; i++) { // Creating element div let array_ele2 = document.createElement("div"); // Adding class 'block2' to div array_ele2.classList.add("block2"); // Adding style to div array_ele2.style.height = `${20}px`; array_ele2.style.transform = `translate(${i * 30}px)`; // Giving indexes let array_ele_label2 = document.createElement("label"); array_ele_label2.classList.add("block_id3"); array_ele_label2.innerText = i; // Appending created elements to index.html array_ele2.appendChild(array_ele_label2); count_container.appendChild(array_ele2); } } // Asynchronous Heapify function async function Heapify(n, i) { let blocks = document.querySelectorAll(".block"); let largest = i; // Initialize largest as root let l = 2 * i + 1; // left = 2*i + 1 let r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if ( l < n && Number(blocks[l].childNodes[0].innerHTML) > Number(blocks[largest].childNodes[0].innerHTML) ) largest = l; // If right child is larger than largest so far if ( r < n && Number(blocks[r].childNodes[0].innerHTML) > Number(blocks[largest].childNodes[0].innerHTML) ) largest = r; // If largest is not root if (largest != i) { let temp1 = blocks[i].style.height; let temp2 = blocks[i].childNodes[0].innerText; blocks[i].style.height = blocks[largest].style.height; blocks[largest].style.height = temp1; blocks[i].childNodes[0].innerText = blocks[largest].childNodes[0].innerText; blocks[largest].childNodes[0].innerText = temp2; await new Promise((resolve) => setTimeout(() => { resolve(); }, 250) ); // Recursively Hapify the affected sub-tree await Heapify(n, largest); } } // Asynchronous HeapSort function async function HeapSort(n) { let blocks = document.querySelectorAll(".block"); // Build heap (rearrange array) for (let i = n / 2 - 1; i >= 0; i--) { await Heapify(n, i); } // One by one extract an element from heap for (let i = n - 1; i > 0; i--) { // Move current root to end let temp1 = blocks[i].style.height; let temp2 = blocks[i].childNodes[0].innerText; blocks[i].style.height = blocks[0].style.height; blocks[0].style.height = temp1; blocks[i].childNodes[0].innerText = blocks[0].childNodes[0].innerText; blocks[0].childNodes[0].innerText = temp2; await new Promise((resolve) => setTimeout(() => { resolve(); }, 250) ); // Call max Heapify on the reduced heap await Heapify(i, 0); } } // Calling generatearray function generatearray(); // Calling generate_idx function generate_idx(); // Calling HeapSort function HeapSort(20); Output: Comment More infoAdvertise with us Next Article Heap Sort Visualization using JavaScript T tk315 Follow Improve Article Tags : Sorting Technical Scripter JavaScript Web Technologies HTML CSS DSA Technical Scripter 2020 HTML-Questions CSS-Questions JavaScript-Questions +7 More Practice Tags : Sorting Similar Reads Heap Sort - Data Structures and Algorithms Tutorials Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use 14 min read Iterative HeapSort HeapSort is a comparison-based sorting technique where we first build Max Heap and then swap the root element with the last element (size times) and maintains the heap property each time to finally make it sorted. Examples: Input : 10 20 15 17 9 21 Output : 9 10 15 17 20 21 Input: 12 11 13 5 6 7 15 11 min read Java Program for Heap Sort Heap sort is a comparison-based sorting technique based on the Binary Heap data structure. It is similar to the selection sort where first find the maximum element and place it at the end. We repeat the same process for the remaining element. Heap Sort in JavaBelow is the implementation of Heap Sort 3 min read C++ Program for Heap Sort Heap sort is a comparison-based sorting technique based on the Binary Heap data structure. It is similar to the selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining element. Recommended PracticeHeap SortTry It! 3 min read sort_heap function in C++ The sort_heap( ) is an STL algorithm which sorts a heap within the range specified by start and end. Sorts the elements in the heap range [start, end) into ascending order. The second form allows you to specify a comparison function that determines when one element is less than another. Defined in h 3 min read Heap Sort - Python Heapsort is a comparison-based sorting technique based on a Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining element.Heap Sort AlgorithmFirst convert the array in 4 min read Lexicographical ordering using Heap Sort Given an array arr[] of strings. The task is to sort the array in lexicographical order using Heap Sort.Examples: Input: arr[] = { "banana", "apple", "mango", "pineapple", "orange" } Output: apple banana mango orange pineappleInput: arr[] = { "CAB", "ACB", "ABC", "CBA", "BAC" } Output: ABC, ACB, BAC 10 min read Heap sort for Linked List Given a linked list, the task is to sort the linked list using HeapSort. Examples: Input: list = 7 -> 698147078 -> 1123629290 -> 1849873707 -> 1608878378 -> 140264035 -> -1206302000Output: -1206302000 -> 7 -> 140264035 -> 1123629290 -> 1608878378 -> 1698147078 ->1 14 min read Python Code for time Complexity plot of Heap Sort Prerequisite : HeapSort Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element. We implement Heap Sort he 3 min read Sorting algorithm visualization : Heap Sort An algorithm like Heap sort can be understood easily by visualizing. In this article, a program that visualizes the Heap Sort Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach: Generate random array and fill the pygame window wi 4 min read Like