Merge Sort Visualization in JavaScript

JavascriptProgramming ScriptsWeb DevelopmentFront End Technology

In this tutorial, we will create a Merge 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 merge sort.

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

Merge Sort in JavaScript

Merge sort is a sorting algorithm that uses the divide & conquers technique. It continuously divides the array into two equal parts until the last array contains only a single value and after performing the divide operation it compares the elements and performs merging.

Basically, in merging process compares both the array elements and performs a sorted merge of both the arrays.

To perform merge sort on the array we have to create two recursive functions one will divide the array and the other will perform the merging operation.

MergeSort() Function

This function will perform a divide operation using the following steps −

Step 1 − This will take an array as an argument, and it will contain a base case if the array has only a single element, then it will return that subarray

Step 2 − using the middle variable divide array into two subarrays left and the right.

Step 3 − pass then both subarrays again to the MergeSort function recursively

Step 4 − To perform merge pass both the arrays into the merge function and return the array.

Merge() Function

This function will take two arrays and by comparing both array values it will perform merging operations using the following steps −

Step 1 − Create an array to store sorted elements, the array will have length as the first array length + second array length.

Step 2 − Using the while loop we will check both array elements until we will be out of both the array index length.

Step 3 − If the current element of the first array is lesser than the second array current the element then adds the first array current value to the sorted array.

Step 4 − Using one more while loop we will push the remaining element of the array which left.

Step 5 − Return the sorted array from the function.

Example 

Let’s add our design to the browser screen.

<html> <head> <title>Merge 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: white; height: 305px; width: 568px; 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">Merge Sort Visualization</p> <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">Sort Array <i class="fa fa-sort"></i></button> <br/><br/> <div id="writeHere"></div> </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 MergeSort(), and it will perform the merge sort operation in that function as we have discussed the approach how it will be working.

Approach

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

Step 1 − Created three arrays first to store initial random generated values, second for in between the program, third to store sorted item performed using merged function.

Step 2 − Display first array random generated value by creating bars with height as array value.

Step 3 − call merge Sort function here Msort will divide the array by splitting array using mid value.

Step 4 − Merge two sorted array into one and add the values into sorted array.

Step 5 − Created box with merged array.

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

Example 

<html> <head> <title>Merge 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: white; height: 305px; width: 568px; 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">Merge 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="MergeSort()">Sort Array <i class="fa fa-sort"></i></button> <br/><br/> <h2 id="writeHere"></h2> </div> <script> const list = [], visited = [], tempArr=[];; for(let i=0;i<20;i++) {tempArr.push(0);visited.push(0);} // display initial array with random values function arrayDisplay(){ var ItemBox = document.getElementById("listItem"); for (var i = 0; i < 20; i++) { list.push(Number(Math.ceil(Math.random() * 80))); } for (var i = 0; i < 20; i++) { var currItem = list[i], element = document.createElement("div"); element.classList.add("box"); element.style.height = `${currItem * 2}px`; element.style.transform = `translate(${i * 30}px)`; var eleUsingLabel = document.createElement("label"); eleUsingLabel.classList.add("box_nm"); eleUsingLabel.textContent = currItem; eleUsingLabel.setAttribute("style", "font-weight: bold;") element.appendChild(eleUsingLabel); ItemBox.appendChild(element); } } // create box after every merging step const MakeBox=async(left, right)=>{ var box = document.querySelectorAll(".box"); var DisplayResult = document.getElementById("writeHere"); DisplayResult.textContent = ""; await new Promise((resolve) =>setTimeout(() => {resolve();}, 300)); document.getElementById("listItem").innerHTML = ""; var ItemBox = document.getElementById("listItem"); for (var i = 0; i <20; i++) { var currItem = list[i], element = document.createElement("div"); element.classList.add("box"); element.style.height = `${currItem * 2}px`; element.style.transform = `translate(${i * 30}px)`; var eleUsingLabel = document.createElement("label"); eleUsingLabel.classList.add("box_nm"); eleUsingLabel.textContent = currItem; eleUsingLabel.setAttribute("style", "font-weight: bold;") element.appendChild(eleUsingLabel); ItemBox.appendChild(element); } let bars=document.querySelectorAll(".box"); for (let i = left; i <= right; i++) { bars[i].style.backgroundColor = " rgb(49, 226, 13)"; } } //merging two sorted subarray function Merge(left, right) { let mid=parseInt((left+right)/2); let left1=left, left2=mid+1; let right1=mid, right2=right; let i=left; //merges subarray while(left1<=right1 && left2<=right2){ if (list[left1] <= list[left2]) { tempArr[i] = list[left1] i = i + 1 left1 = left1 + 1; } else if(list[left1] > list[left2]) { tempArr[i] = list[left2] i = i + 1 left2 = left2 + 1; } } while (left1 <= right1) { tempArr[i] = list[left1] i = i + 1 left1 = left1 + 1; } while (left2 <= right2) { tempArr[i] = list[left2] i = i + 1 left2 = left2 + 1; } i = left; while (i <= right) { list[i] = tempArr[i]; i++; } } // asynchronous timeout function to create delay between two boxes function Createtimeout(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // merge sort function const Msort = async(left, right)=>{ if(left<right){ let mid=parseInt((left+right)/2) await Msort(left, mid); await Msort(mid+1, right); await Merge(left, right); await MakeBox(left, right); await Createtimeout(200) } } const MergeSort=async()=>{ await Msort(0, 19) document.getElementById("writeHere").innerHTML="MergeSort applied Successfully." } </script> </body> </html>

So, we got to know about merge sort visualization program.

raja
Updated on 11-Oct-2022 09:12:17

Advertisements