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:
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.
- The new array can be generated by pressing the “Ctrl+R” key.
- The sorting is performed using BubbleSort() function using the swap() function
Example: Here is the implementation of the above-explained steps.

Below is the program to visualize the Bubble Sort algorithm.
index.html
HTML
| <!DOCTYPE html><htmllang="en"><head>    <metacharset="UTF-8"/>    <metaname="viewport"content=        "width=device-width, initial-scale=1.0"/>    <linkrel="stylesheet"href="style.css"/></head><body>    <br/>    <pclass="header">Bubble Sort</p>    <divid="array"></div>    <scriptsrc="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: 413px;    width: 598px;    margin: auto;    position: relative;    margin-top: 64px;}.block{    width: 28px;    background-color: #6b5b95;    position: absolute;    bottom: 0px;    transition: 0.2s allease;}.block_id {    position: absolute;    color: black;    margin-top: -20px;    width: 100%;    text-align: center;} | 
script.js: The following is the content for “script.js” file used in the above HTML code.
javascript
| varcontainer = document.getElementById(& quot; array & quot;);// Function to generate the array of blocksfunctiongeneratearray() {    for(vari = 0; i & lt; 20; i++) {        // Return a value from 1 to 100 (both inclusive)        varvalue = Math.ceil(Math.random() * 100);        // Creating element div        vararray_ele = document.createElement(& quot; div & quot;);        // Adding class 'block' to div        array_ele.classList.add(& quot; block & quot;);        // 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        vararray_ele_label = document.createElement(& quot; label & quot;);        array_ele_label.classList.add(& quot; block_id & quot;);        array_ele_label.innerText = value;        // Appending created elements to index.html         array_ele.appendChild(array_ele_label);        container.appendChild(array_ele);    }}// Promise to swap two blocksfunctionswap(el1, el2) {    returnnewPromise((resolve) =& gt; {        // For exchanging styles of two blocks        vartemp = el1.style.transform;        el1.style.transform = el2.style.transform;        el2.style.transform = temp;        window.requestAnimationFrame(function() {            // For waiting for .25 sec            setTimeout(() =& gt; {                container.insertBefore(el2, el1);                resolve();            }, 250);    });});}// Asynchronous BubbleSort functionasync functionBubbleSort(delay = 100) {    varblocks = document.querySelectorAll(& quot;.block & quot;);    // BubbleSort Algorithm    for(vari = 0; i & lt; blocks.length; i += 1) {        for(varj = 0; j & lt; blocks.length - i - 1; j += 1) {            // To change background-color of the            // blocks to be compared            blocks[j].style.backgroundColor = & quot;#FF4949 & quot;;            blocks[j + 1].style.backgroundColor = & quot;#FF4949 & quot;;            // To wait for .1 sec            await newPromise((resolve) =& gt;            setTimeout(() =& gt; {                resolve();            }, delay)            );            console.log(& quot; run & quot;);            varvalue1 = Number(blocks[j].childNodes[0].innerHTML);            varvalue2 = Number(blocks[j + 1]                .childNodes[0].innerHTML);            // To compare value of two blocks            if(value1 & gt; value2) {                await swap(blocks[j], blocks[j + 1]);                blocks = document.querySelectorAll(& quot;.block & quot;);            }            // Changing the color to the previous one            blocks[j].style.backgroundColor = & quot;#6b5b95 & quot;;            blocks[j + 1].style.backgroundColor = & quot;#6b5b95 & quot;;        }        //changing the color of greatest element         //found in the above traversal        blocks[blocks.length - i - 1]            .style.backgroundColor = & quot;#13CE66 & quot;;    }}// Calling generatearray functiongeneratearray();// Calling BubbleSort functionBubbleSort(); | 
Output:
                                            Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
 
				 
					


