# Insertion Sort Visualization 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 an Insertion sort visualization program 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 Insertion sort.

Before let’s first get to know about what Insertion sort is.

## Insertion Sort in JavaScript

Insertion sort is a sorting algorithm that uses the sorted and unsorted array technique. We simply divide the array into the sorted and unsorted portion, and we take an item from the unsorted array then compare It with the sorted array part if found larger than the current item then doesn’t do anything, if found smaller than the previous sorted element than we insert it to correct position.

Insertion sort is an in-place algorithm that doesn’t use any additional memory space, instead, it performs an operation on itself and rewrites the original memory location. It is a comparison-based algorithm.

## Step by step to perform insertion Sort

Step 1 − Divide the array into two parts sorted and the unsorted array so we start by considering the first element as sorted as a single element is always sorted.

Step 2 − Take the first element of the unsorted array into a temporary variable.

Step 3 − Perform a comparison of a temporary variable with all the sorted array, in case we find temporary variable as smaller than the sorted array element then sift all the sorted array value from left to right and insert the temporary variable value in the sorted array.

### Example

Let’s take an array with elements 7 4 5 2 6

We will consider first which is index=0 element as sorted because single element is always sorted. (Here values before | sign is sorted).

Index=0 element=7
Sorted | unsorted
7 | 4 5 2 6

Index=1 element=4
Compare the element value which is 4 with sorted array values and insert when we found element is smaller than the value and stop the operation.

Sorted | unsorted
4 7 | 5 2 6

Index =2 element=5
Compare the element value which is 5 with sorted array values and insert when we found element is smaller than the value and stop the operation

Sorted | unsorted
4 5 7 | 2 6

Index=3 element=2
Compare the element value which is 2 with so rted array values and insert when we found element is smaller than the value and stop the operation

Sorted | unsorted
2 4 5 7 | 6

Index=4 element=6
Compare the element value which is 6 with sorted array values and insert when we found element is smaller than the value and stop the operation

Sorted | unsorted
2 4 5 6 7

Finally, our sorted array values after insertion sort are 2 4 5 6 7.


## Add our HTML & CSS design to the browser screen.

### Example

<html>
<title>Insertion Sort visualization using JavaScript.</title>
<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>
<body>
<br/>
<h2 style="font-family: cursive; text-align:center">Insertion 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="InsertionSort()">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 InsertionSort() and it will perform the Insertion sort operation 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 step −

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 Insertion Sort function to perform algorithm operation on the array.

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

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

### Example

Full Insertion sort program

<html>
<title>Insertion Sort visualization using JavaScript.</title>
<style>
#listItem {
position: relative;
margin-top: 64px;
background-color: white;
height: 305px;
width: 568px;
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>
<body>
<br/>
<h2 style="font-family: cursive; text-align:center">Insertion 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="InsertionSort()">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.style.height = ${currItem * 2}px; element.style.transform = translate(${i * 30}px);
let eleUsingLabel = document.createElement("label");
eleUsingLabel.textContent = currItem;
eleUsingLabel.setAttribute("style", "font-weight: bold;")
element.appendChild(eleUsingLabel);
ItemBox.appendChild(element);
}
}
function Createtimeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// insertion sort function
const InsertionSortFunction=async()=>{
let ElementBox = document.querySelectorAll(".ElementBox");
ElementBox[0].style.backgroundColor="#32CD30"
let ItemBox = document.getElementById("listItem");
for (let i = 1; i < 20; i++) {
ElementBox[i].style.backgroundColor = "red";
await Createtimeout(600);
let ElementLabel = parseInt(ElementBox[i].childNodes[0].innerHTML);
let h= ElementBox[i].style.height;
let j = i-1;
while ((j >=0) && parseInt(ElementBox[j].childNodes[0].innerHTML)>ElementLabel) {
ElementBox[j].style.backgroundColor = "red";
ElementBox[j + 1].style.height = ElementBox[j].style.height;
ElementBox[j + 1].childNodes[0].innerText =
ElementBox[j].childNodes[0].innerText;

//list[j+1] = list[j];
j--;
Createtimeout(600);
let colorIndex=i;
while(colorIndex>=0){
ElementBox[colorIndex].style.backgroundColor = "yellow";
colorIndex--;
}
}
ElementBox[j + 1].style.height = h;
ElementBox[j + 1].childNodes[0].innerHTML = ElementLabel;
Createtimeout(600);
ElementBox[i].style.backgroundColor = "yellow";
}
document.getElementById("writeHere").innerHTML="Insertion Sort applied Successfully."
}
const InsertionSort=async()=>{
await InsertionSortFunction()
}
</script>
</body>
</html>


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

Updated on 11-Oct-2022 09:36:23