Insertion Sort Visualization using JavaScript Last Updated : 23 Feb, 2021 Comments Improve Suggest changes Like Article Like Report 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 codes. In this article, Insertion Sort Visualizer is implemented using HTML, CSS & JavaScript. Pre-requisites: Insertion Sort.Basic HTML,CSS & JavaScript.promises in JavaScript.async/await function in JavaScript. Approach: Button Generate New Array generate an array of random values using Math.random() function and a bar corresponding to that value in terms of height.Different colors are used to indicate which elements are unsorted(sky-blue), compared(darkblue) & sorted(lightgreen).Button Insertion Sort sort the elements using selection sort algorithm.Finally, elements are sorted. Examples: Click Generate New Array button to generate a new random array.Click Selection Sort button to perform Visualization. HTML <!DOCTYPE html> <html lang="en"> <!-- head --> <head> <!-- linking style.css --> <link href="style.css" rel="stylesheet" /> </head> <!-- body --> <body> <section class="head">Insertion Sort</section> <section class="data-container"></section> <section id="ele"></section> <div style="margin: auto; width: fit-content;"> <!-- "Generate New Array" button --> <button class="btn1" onclick="generate()" id="Button1" > Generate New Array</button> <!-- "Insertion Sort" button --> <button class="btn2" onclick="InsertionSort(),disable()" id="Button2" > Insertion Sort</button> </div> </body> <!-- linking index.js --> <script src="index.js"></script> </html> CSS .mySlides { display: none; } body { background-color: rgb(255, 235, 211); font-family: Verdana, sans-serif; } .head { margin-top: 20px; margin-right: 20vw; margin-left: 20vw; text-align: center; font-size: 30px; background-color: #6f459e; color: white; border-radius:19px; font-weight: bolder; } .data-container { width: 600px; height: 364px; position: relative; margin: 0 auto; } .bar { width: 28px; position: absolute; left: 0; bottom: 0; background-color: rgb(0, 183, 255); transition: 0.2s all ease; } .bar__id { position: absolute; top: -24px; width: 100%; text-align: center; } .btn1 { padding: 12px; font-weight: bolder; background-color: #6f459e; border-radius: 10px; color: white; font-size: 16px; border: white; margin-top: 1vw; margin-right: 1vw; } .btn2 { padding: 12px; font-weight: bolder; background-color: #6f459e; border-radius: 10px; color: white; font-size: 16px; border: white } #ele{ text-align: center; height: 35px; } JavaScript const container = document.querySelector(".data-container"); // Function to generate bars function generatebars(num = 20) { //For loop to generate 20 bars for (let i = 0; i < num; i += 1) { // To generate random values from 1 to 100 const value = Math.floor(Math.random() * 100) + 1; // To create element "div" const bar = document.createElement("div"); // To add class "bar" to "div" bar.classList.add("bar"); // Provide height to the bar bar.style.height = `${value * 3}px`; // Translate the bar towards positive X axis bar.style.transform = `translateX(${i * 30}px)`; // To create element "label" const barLabel = document.createElement("label"); // To add class "bar_id" to "label" barLabel.classList.add("bar__id"); // Assign value to "label" barLabel.innerHTML = value; // Append "Label" to "div" bar.appendChild(barLabel); // Append "div" to "data-container div" container.appendChild(bar); } } // Asynchronous function to perform "Insertion Sort" async function InsertionSort(delay = 600) { let bars = document.querySelectorAll(".bar"); // Provide lightgreen colour to 0th bar bars[0].style.backgroundColor = " rgb(49, 226, 13)"; for (var i = 1; i < bars.length; i += 1) { // Assign i-1 to j var j = i - 1; // To store the integer value of ith bar to key var key = parseInt(bars[i].childNodes[0].innerHTML); // To store the ith bar height to height var height = bars[i].style.height; // For selecting section having id "ele" var barval=document.getElementById("ele") // For dynamically Updating the selected element barval.innerHTML= `<h3>Element Selected is :${key}</h3>`; //Provide darkblue color to the ith bar bars[i].style.backgroundColor = "darkblue"; // To pause the execution of code for 600 milliseconds await new Promise((resolve) => setTimeout(() => { resolve(); }, 600) ); // For placing selected element at its correct position while (j >= 0 && parseInt(bars[j].childNodes[0].innerHTML) > key) { // Provide darkblue color to the jth bar bars[j].style.backgroundColor = "darkblue"; // For placing jth element over (j+1)th element bars[j + 1].style.height = bars[j].style.height; bars[j + 1].childNodes[0].innerText = bars[j].childNodes[0].innerText; // Assign j-1 to j j = j - 1; // To pause the execution of code for 600 milliseconds await new Promise((resolve) => setTimeout(() => { resolve(); }, 600) ); // Provide lightgreen color to the sorted part for(var k=i;k>=0;k--){ bars[k].style.backgroundColor = " rgb(49, 226, 13)"; } } // Placing the selected element to its correct position bars[j + 1].style.height = height; bars[j + 1].childNodes[0].innerHTML = key; // To pause the execution of code for 600 milliseconds await new Promise((resolve) => setTimeout(() => { resolve(); }, 600) ); // Provide light green color to the ith bar bars[i].style.backgroundColor = " rgb(49, 226, 13)"; } barval.innerHTML="<h3>Sorted!!!</h3>"; // To enable the button // "Generate New Array" after final(sorted) document.getElementById("Button1") .disabled = false; document.getElementById("Button1") .style.backgroundColor = "#6f459e"; // To enable the button // "Insertion Sort" after final(sorted) document.getElementById("Button2") .disabled = false; document.getElementById("Button2") .style.backgroundColor = "#6f459e"; } // Call "generatebars()" function generatebars(); // Function to generate new random array function generate() { window.location.reload(); } // Function to disable the button function disable() { // To disable the button "Generate New Array" document.getElementById("Button1") .disabled = true; document.getElementById("Button1") .style.backgroundColor = "#d8b6ff"; // To disable the button "Insertion Sort" document.getElementById("Button2") .disabled = true; document.getElementById("Button2") .style.backgroundColor = "#d8b6ff"; } Output: [embed]https://media.geeksforgeeks.org/wp-content/uploads/20210203144011/Insertion-Sort-Visualizer--video.mp4[/embed] Comment More infoAdvertise with us Next Article Insertion Sort Visualization using JavaScript S shivammahajancse Follow Improve Article Tags : Sorting Technical Scripter JavaScript Web Technologies DSA Technical Scripter 2020 Insertion Sort +3 More Practice Tags : Sorting Similar Reads 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 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 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 Bubble Sort Visualization using JavaScript GUI(Graphical User Interface) helps in better understanding than programs. In this article, we will visualize Bubble Sort using JavaScript. We will see how the elements are swapped in Bubble Sort and how we get the final sorted array. We will also visualize the time complexity of Bubble Sort. Refer 4 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 Gnome Sort Visualizer using JavaScript In this article, we are going to learn Gnome sort Visualizer using javascript, Gnome Sort also called Stupid sort, is based on the concept of a Garden Gnome sorting his flower pots. In order to know more about it. Please refer to Gnome Sort.An algorithm like Gnome Sort can be easily understood by vi 4 min read Insertion Sort Visualization using Matplotlib in Python Prerequisites: Insertion Sort, Using Matplotlib for Animations Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. For this we will use matplotlib, to plot bar graphs to represent the elements 3 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 Ternary Search Visualization using JavaScript 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 Se 4 min read 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 Like