Problem: I’m building a website to visualize sorting algorithms using vanilla JavaScript. When I click the “Sort” button twice, the algorithm starts sorting the same array twice, causing unexpected behavior in the visualization.
What I Have Tried: I suspect this is because the event listener for the “Sort” button is being triggered multiple times, but I haven’t been able to resolve the issue.
Here is the code:
async function handleBubbleSort() {
const container = document.getElementById("bubble-array-container");
const elements = container.getElementsByClassName("array-element");
let i = 0;
let j = 0;
async function step() {
if (i < elements.length) {
if (j < elements.length - i - 1) {
const currentElement = elements[j];
const nextElement = elements[j + 1];
currentElement.style.backgroundColor = "var(--current-color)";
nextElement.style.backgroundColor = "var(--next-color)";
currentElement.style.color = "black";
nextElement.style.color = "black";
await new Promise((resolve) => setTimeout(resolve, 1000));
const currentValue = parseInt(currentElement.innerHTML);
const nextValue = parseInt(nextElement.innerHTML);
if (currentValue > nextValue) {
await swapElements(currentElement, nextElement);
}
currentElement.style.backgroundColor = "var(--default-color)";
nextElement.style.backgroundColor = "var(--default-color)";
j++;
await step();
} else {
elements[elements.length - i - 1].style.backgroundColor =
"var(--sorted-color)";
j = 0;
i++;
await step();
}
} else {
console.log("Array Sorted Successfully");
}
}
await step();
}
and HTML:
<h3>Bubble Sort</h3>
<div class="label-container">
<div class="label current-element">
<div class="color-box"></div>
<span> Current </span>
</div>
<div class="label next-element">
<div class="color-box"></div>
<span> Next </span>
</div>
<div class="label sorted-element">
<div class="color-box"></div>
<span>Sorted</span>
</div>
</div>
<div class="array-container" id="bubble-array-container"></div>
<div class="button-group">
<button class="new-button" onclick="generateNewArray('bubble')">
Generate New Array
</button>
<button class="sort-button" onclick="handleBubbleSort()">Sort</button>
</div>
</div>```