Visualization of the Insertion Sort algorithm Project using HTML5, CSS, and JavaScript content

Creating a visualization of the Insertion Sort algorithm using HTML, CSS, and JavaScript allows you to see how this sorting algorithm works step by step. In this visualization, we’ll represent an array of values as vertical bars that gradually become sorted.

Visualization of the Insertion Sort

Creating a visualization of the Insertion Sort algorithm using HTML, CSS, and JavaScript allows you to see how this sorting algorithm works step by step. In this visualization, we’ll represent an array of values as vertical bars that gradually become sorted. Here’s a step-by-step description of how it works:

Insertion Sort is a simple sorting algorithm that works by iterating over the array from left to right. For each element in the array, the algorithm compares the element to the previous element. If the current element is smaller than the previous element, the algorithm swaps the two elements. The algorithm continues iterating over the array until it reaches the end.

HTML for Visualization of the Insertion Sort

Visualization of the Insertion Sort The HTML code for the visualization will create a simple web page with two buttons: one to generate a new array and one to sort the array using the Insertion Sort algorithm. It will also create a container element for the array visualization.

CSS for Visualization of the Insertion Sort

The CSS code for the visualization will style the web page and the array visualization container.

JavaScript for Visualization of the Insertion Sort

The JavaScript code for the visualization will generate a new array of random numbers, sort the array using the Insertion Sort algorithm, and update the array visualization.

  • JavaScript contains the logic for the Insertion Sort algorithm and the visualization process.
  • The insertionSort function performs the sorting. It uses a sleep function to add delays for visualization, making it easier to follow the sorting process.
  • The bars representing array elements are updated in the DOM during the sort, changing their heights to reflect their values. Bars being moved are highlighted in red, and once they find their sorted positions, they turn green.
  • The generateArray function creates a random array of values and initializes the visualization.
  • The startSorting function is triggered when the “Start Sorting” button is clicked. It generates a new random array and sorts it using the insertionSort function.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    body{
        font-size: 1.5rem;
    }
    .container{
        margin-top: 100px;
        margin-right: auto;
        margin-left: auto;
        /* padding: auto; */
        width: 80%;
        min-width: 360px;
         /* display: flex; */
    }
    .array-input-lable{
        display: block;
        margin-bottom: 10px;
    }
    .array-input{
        display: block;
        height: 50px;
        box-sizing: border-box;
        outline: none;
        width: 600px;
        max-width: 100%;
        padding-left: 10px;
        border-radius: 5px;
        border: 1px solid black;
        font: inherit;
        margin-bottom: 10px;
    }
    .submit-array{
        height: 40px;
        border-radius: 5px;
        border: none;
        color: white;
        background-color: #09a0aa;
        font: inherit;
        width: 600px;
        max-width: 100%;
    }
    .submit-array:hover{
        background-color: #06585e;
        transform: scale(1.02);
    }
    .array-input:focus{
        border: 1px solid #09a0aa;
        box-shadow: 0 0 5px #09a0aa;
    }
    .input-error{
        color: red;
    }
    .array{
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 10px;
    }
    .array-element{
        box-sizing: border-box;
        height: 50px;
        padding: 10px;
        border: 1px solid black;
        border-radius: 5px;
        margin-right: 10px;
        margin-bottom: 10px;
    }
    .array-element.swapped{
        border-color: red;
        box-shadow: 0 0 5px red;
    }
    .array-element.compared{
        border-color: blue;
        box-shadow: 0 0 5px blue;
    }
    .comparing{
        color: blue;
    }
    .swapping{
        color: red;
    }
    /* .right{
        margin-left: 100px;
    } */
</style>
<body>
    <div class="container">
        <div class="left">
        <h2>Insertion Sort Simulator</h2>
        <h3>Array Input</h3>
        <input class="array-input" id="array-input" placeholder="Enter numbers, seperated by spaces...">
        <button class="submit-array" id="submit-array">Sort</button>
        <div class="input-error" id="input-error"></div>
    </div>
    <div class="right">
        <h3>Array Output</h3>
        <div class="array" id="array"></div>
        <div class="array1" id="array1"></div>
        <div class="status" id="status"></div>
    </div>
    </div>
    <script>
        const sleep = async (ms) => {
            return new Promise(resolve => setTimeout(resolve, ms));
        }
        const parseArrayInput = (inputStr) => {
            const tokens = inputStr.trim().split(/\s+/);
            const array = tokens.map(elem => parseFloat(elem));
            if(array.length !== tokens.length || array.some(elem => isNaN(elem)))
                return null;
            return array;
        }
        const insertArrayToHtml = (array) => {
            const html = '<div class="array-element">' +
                array.join('</div><div class="array-element">') +
                    '</div>';
            document.getElementById('array').innerHTML = html;
        }
        const insertArrayToHtml1 = (array) => {
            const html = '<div class="array-element">' +
                array.join('</div><div class="array-element">') +
                    '</div>';
            document.getElementById('array1').innerHTML = array;
        }
        const highlightElements = (i, j, additionalClass) => {
            const array = document.getElementById('array').children;
            array[i].classList.add(additionalClass);
            array[j].classList.add(additionalClass);
        }
        const setStatus = (status) => {
            const statusElem = document.getElementById('status');
            statusElem.innerHTML = status === 'comparing' ? 'Comparing...' : 'Swapping...';
            statusElem.className = status;
        }
        const bubbleSort = async () => {
            const array = parseArrayInput(document.getElementById('array-input').value);
            if(!array){
                document.getElementById('input-error').innerHTML = 'Incorrect input!';
                return;
            }
            document.getElementById('input-error').innerHTML = '';
            const n = array.length;
            for(let i = 1;i <n ;i++){
                for(let j = i;j >0;j--){
                    insertArrayToHtml(array);
                    highlightElements(j, j - 1, 'compared');
                    setStatus('comparing');
                    await sleep(2000);
                    if(array[j] < array[j - 1])
                    {
                        [array[j], array[j -1]] = [array[j - 1], array[j]];
                        insertArrayToHtml(array);
                        highlightElements(j, j - 1, 'swapped');
                        setStatus('swapping');
        }
            //  document.getElementById('array').innerHTML = html;
                        console.log(array);
                        // for (let i = 0; i < array.length; i++){
                        //     insertArrayToHtml(array);
                        // }
                        await sleep(2000);
                    }
                    insertArrayToHtml(array);
                }
            insertArrayToHtml(array);
            document.getElementById('status').innerHTML = '';
            }
        document.getElementById('submit-array').addEventListener('click', bubbleSort);
    </script>
</body>
</html>
Scroll to Top