This particular function is designed to navigate through the dataset and arrange it in ascending order.
The intended behavior is for the sorting process to stop once the entire list has been sorted. However, the use of the !changed
control flow statement causes premature termination, resulting in only one iteration being completed. How can I modify the code so that the sorting continues until the entire dataset is sorted?
// Implementation of Bubble Sort algorithm
function bubble_sort() {
sort.addEventListener("click", function() {
const dataList = document.querySelectorAll(".data");
let delay = 0;
for (let i = 0; i < dataList.length - 1; i++) {
let changed = false;
for (let j = 0; j < dataList.length - 1 - i; j++) {
setTimeout(() => {
let value1 = parseInt(dataList[j].getAttribute("value"));
let value2 = parseInt(dataList[j + 1].getAttribute("value"));
// Visualize the comparison by highlighting the elements
dataList[j].style.backgroundColor = "blue";
dataList[j + 1].style.backgroundColor = "blue";
if (value1 > value2) {
// Swap the values and heights
let tempHeight = dataList[j].style.height;
let tempValue = dataList[j].getAttribute("value");
dataList[j].style.height = dataList[j + 1].style.height;
dataList[j].setAttribute("value", dataList[j + 1].getAttribute("value"));
dataList[j + 1].style.height = tempHeight;
dataList[j + 1].setAttribute("value", tempValue);
changed = true;
}
// Reset the background color after comparison
setTimeout(() => {
dataList[j].style.backgroundColor = "black";
dataList[j + 1].style.backgroundColor = "black";
}, speed/2);
}, delay);
delay += speed;
}
if (!changed) {
return;
}
}
});
}
An attempt was made to introduce a variable to monitor whether the ordering has changed. However, due to the delay in execution, the checking occurs prematurely.
There was an effort to address this issue using the setTimeout
method:
setTimeout(() => {
console.log(changed)
if (!changed) {
return;
}
}, (dataList.length - i - 1) * delay);
Although my approach included this adjustment, it did not produce the desired outcome (possibly because of miscalculations on my part)?