Unlocking the Magic of Algorithms: An Algorithm Visualizer Project


This simple example creates a visual representation of the Bubble Sort algorithm. The HTML file includes a container with bars representing elements to be sorted. The CSS file styles these bars, and the JavaScript file contains the logic for the Bubble Sort algorithm and animation. When you click the "Sort" button, the algorithm is executed and visually shown in action.

Remember to adjust the await sleep(100) line in the swap function to control the visualization speed. You can lower or increase the sleep time to make the visualization faster or slower.


 HTML:

<!DOCTYPE html>

<html>

<head>

  <title>Algorithm Visualizer - Bubble Sort</title>

  <link rel="stylesheet" type="text/css" href="styles.css">

</head>

<body>

  <h1>Algorithm Visualizer - Bubble Sort</h1>

  <div class="container">

    <div class="bar" style="height: 100px;"></div>

    <div class="bar" style="height: 80px;"></div>

    <div class="bar" style="height: 60px;"></div>

    <div class="bar" style="height: 40px;"></div>

    <div class="bar" style="height: 20px;"></div>

  </div>

  <button onclick="bubbleSort()">Sort</button>

  <script src="script.js"></script>

</body>

</html>


CSS (styles.css):

body {

  text-align: center;

  font-family: Arial, sans-serif;

}

.container {

  display: flex;

  justify-content: center;

  align-items: flex-end;

  height: 150px;

}

.bar {

  width: 20px;

  background-color: #007bff;

  margin: 0 2px;

}


button {

  margin-top: 20px;

}


JavaScript (script.js):

function sleep(ms) {

  return new Promise(resolve => setTimeout(resolve, ms));

}

async function swap(el1, el2) {

  const style1 = window.getComputedStyle(el1);

  const style2 = window.getComputedStyle(el2);

  const transform1 = style1.getPropertyValue("height");

  const transform2 = style2.getPropertyValue("height");

  el1.style.height = transform2;

  el2.style.height = transform1;

  await sleep(100); // Adjust the delay here for visualization speed

}

async function bubbleSort() {

  const bars = document.querySelectorAll(".bar");

  const len = bars.length;

  for (let i = 0; i < len; i++) {

    for (let j = 0; j < len - i - 1; j++) {

      const bar1 = bars[j];

      const bar2 = bars[j + 1];

      bar1.style.backgroundColor = "red"; // Highlight the current comparison

      if (parseInt(bar1.style.height) > parseInt(bar2.style.height)) {

        await swap(bar1, bar2);

      }

      bar1.style.backgroundColor = "#007bff"; // Reset the color after comparison

    }

    bars[len - i - 1].style.backgroundColor = "#00ff00"; // Highlight the sorted bar

  }

}

Comments