How to Visualize Quick Sort using Lomuto Partition in JavaScript?

JavascriptProgramming ScriptsWeb DevelopmentFront End Technology

In this tutorial, we will create Quick sort visualization of the Lomuto partition method 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 quick sort.

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

Quick Sort in JavaScript

Quick sort is a sorting technique that works on divide and conquer method same as merge sort. Basically, we take a random element as pivot which will help to divide the element and we partition the array.

What is Lomuto Partition?

Let’s first get to know about what lomuto partition does.

Lomuto partition takes a pivot element as the last element which is (n-1) th index of the array and compare it with all the elements and put the pivot element at its correct position such that- All the element are smaller or equal to the pivot element will come it’s left side and all the greater element than the pivot will come to its right side.

So, we will divide the array using the QuickSort function and in every part of the array, we will arrange the pivot element in such a way that an element smaller than the pivot will come to its left side and greater will come to its right side.

Algorithm of quicksort function

QuickSort(array, low, high){ if(low<high){ int partition_index= Partition_Lomuto(array, low, high); QuickSort(array, low, partition_index-1); QuickSort(array, partition_index+1, high); } }

Algorithm of Partition function

Partition_Lomuto(array, low, high){ pivot_element= arr[high]; index=low-1; //index of smaller element for(i=low;i<high;i++){ if(array[i]<pivot_element){ index++; swap(array[i], array[index]); } } //after comparison being the pivot at its correct position swap(array[i+1], array[high]); return index+1; }

Step by step to perform quick sort

Quick Sort function

Step 1 − Take last element as pivot

Step 2 − Partition the array using pivot index

Step 3 − Quicksort left side value from left to pivot 1

Step 4 − Quicksort right side array from pivot to right

Partition function

Step 1 − Take last element as pivot

Step 2 − Take left and right two variables left as lower index and right as higher.

Step 3 − Compare if left side value is lesser than pivot value- move right & repeat.

Step 4 − Compare if right side value is greater than pivot -move left &repeat.

Step 5 − After step 3,4 swap left and right value element.

Add our HTML & CSS design to the browser screen.

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

<html> <head> <title>QuickSort 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">Quick 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="QSort()">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 QSort() and it will perform the Quick sort operation by calling QuickSort() 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 Quick Sort function to perform algorithm operations on the array.

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

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

Example

Full Quick sort program

<html> <head> <title>QuickSort 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">Quick 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="QSort()">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); } } //set time out function of specified time function Createtimeout(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } //Lomuto Partition function const Partition_Lomuto=async(low, high)=>{ let ElementBox = document.querySelectorAll(".ElementBox"); ElementBox[high].style.backgroundColor="#F51720" let pivot_element=Number(ElementBox[high].childNodes[0].innerHTML); let index=low-1; //index of smaller element for(j=low;j<=high-1;j++){ ElementBox[j].style.backgroundColor = "yellow"; await new Promise((resolve) => setTimeout(() => { resolve(); }, 600) ); if(Number(ElementBox[j].childNodes[0].innerHTML)<pivot_element){ index++; var ElementBox_height_temp = ElementBox[index].style.height; var ElementBox_label_value = ElementBox[index].childNodes[0].innerText; ElementBox[index].style.height = ElementBox[j].style.height; ElementBox[j].style.height = ElementBox_height_temp; ElementBox[index].childNodes[0].innerText =ElementBox[j].childNodes[0].innerText; ElementBox[j].childNodes[0].innerText = ElementBox_label_value; ElementBox[index].style.backgroundColor="orange" if (index != j) ElementBox[j].style.backgroundColor = "#0C2D48"; Createtimeout(600); } // element is >=pivot else{ ElementBox[j].style.backgroundColor = "#0C2D48"; } } //after comparison bring the pivot at its correct position index++; var ElementBox_height_temp = ElementBox[index].style.height; var ElementBox_label_value = ElementBox[index].childNodes[0].innerText; ElementBox[index].style.height = ElementBox[high].style.height; ElementBox[high].style.height = ElementBox_height_temp; ElementBox[index].childNodes[0].innerText =ElementBox[high].childNodes[0].innerText; ElementBox[high].childNodes[0].innerText = ElementBox_label_value; ElementBox[high].style.backgroundColor = "#0C2D48"; ElementBox[index].style.backgroundColor = "green"; await new Promise((resolve) => setTimeout(() => { resolve(); }, 600 * 3) ); for (var k = 0; k < 20; k++) ElementBox[k].style.backgroundColor = "#050A30"; return index; } // Quicksort sort function const QuickSort=async(low, high)=>{ if(low<high){ let pivot_index= await Partition_Lomuto(low, high); await QuickSort(low, pivot_index-1); await QuickSort(pivot_index+1, high); } } //function to call quicksort const QSort=async()=>{ await QuickSort(0, 19); document.getElementById("writeHere").innerHTML="QuickSort applied Successfully." } </script> </body> </html>

So, we got to know about the Quick Sort visualization program.

raja
Updated on 11-Oct-2022 09:29:39

Advertisements