Ending the Bubble Sort process once the data set has been fully sorted

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)?

Answer №1

The issue lies in the difference between setTimeout and sleep in Python. While setTimeout simply schedules code to run after a delay, it does not pause the execution of the surrounding code as sleep does. This can sometimes result in unexpected outcomes.

To address this, we can refactor the loop into an async function and utilize await with setTimeout to properly manage the timing. By doing so, we can effectively pause the code execution for the desired duration:

// Function to create a delay
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// Implement Bubble Sort algorithm
async function bubble_sort() {
    sort.addEventListener("click", async function() {  // asynchronous function declaration
        const dataList = document.querySelectorAll(".data");

        for (let i = 0; i < dataList.length - 1; i++) {
            let changed = false;
            for (let j = 0; j < dataList.length - 1 - i; j++) {
                let value1 = parseInt(dataList[j].getAttribute("value"));
                let value2 = parseInt(dataList[j + 1].getAttribute("value"));

                // Highlight the pair being compared
                dataList[j].style.backgroundColor = "blue";
                dataList[j + 1].style.backgroundColor = "blue";

                if (value1 > value2) {
                    // Swap heights and values
                    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;
                }

                await sleep(speed); // Delay for 'speed' milliseconds

                // Reset color after comparison
                dataList[j].style.backgroundColor = "black";
                dataList[j + 1].style.backgroundColor = "black";

                await sleep(speed / 2); // Wait before resetting colors
            }
            if (!changed) {
                break;
            }
        }
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node/Express API returning empty body when being accessed through fetch or axios requests

Currently working on integrating an API call in a React app using Node/Express. No matter where I place the fetch/axios call, the parsed body always shows up as undefined in my controller. Yesterday, I was experimenting with fetch but decided to switch to ...

Can content be dynamically loaded through ajax in Simile Timeline instead of being loaded upfront?

I am currently utilizing the JavaScript Simile Timeline which includes timeline items with extensive description fields. Rather than including all this information in the initial JSON payload data, I only want to load it when a user clicks on a timeline it ...

In a production setting, Remix js is experiencing a 403 error when attempting to make a POST request, although it functions properly in a local

While working on my remix.js project, I encountered a 403 forbidden error when making a POST request in the production environment. However, everything works fine in the local environment. Here is the request payload Below are the details of the error, p ...

Implement a feature in Vue.js using vee-validate to dynamically add an element when a form field is validated

When using vee-validate, a Vue.js plugin for form validation, my goal is to display an image after the input field has been validated. I attempted to achieve this using v-show="!errors.has('fname')". However, the issue arises when the image appea ...

Extracting input value using HTML and JavaScript

Is there a way to utilize the content of a form field within a confirmation dialog box that pops up upon submission, as illustrated below? <form action='removefinish.php' method='post' accept-charset='UTF-8'> Role: < ...

initiate dynamic elements triggering in jQuery

function fetchTeacherAnnouncementDetails(){ var tCounter = 1; $.ajax({ url:'<%=contextPath%>/show/announcementsForTeacher', headers: { 'Authorization':'${sessionScope.token}' ...

Implement a mouseover event on the axis label using D3.js and JavaScript

Is it possible to trigger a mouseover event on the y-axis label in a chart? For instance, let's say we have a scatter plot with labels "area1", "area2", and "area3" on the y-axis. When a user hovers over the label "area1", a tooltip should appear disp ...

Mocha: A Unique Perspective on Testing the express.Router Instance

As I was developing a JavaScript controller file, I came across the need to test if my controller instance contains an instance of the express method called Router(). import {assert} from 'chai'; import {UF_Controller} from '../../controlle ...

Issues with premature execution of Angular JS code have been observed at times

Currently facing an issue with my code where the updateProduct() function call is happening before the forEach loop begins running on about 1 out of every 10 page loads. Not sure why this is occurring or how to solve it. Any insights on what might be causi ...

JS Issue with triggering .click() function

I'm currently incorporating dropzone.js to enable file uploads. In my setup, I have a button with the id #btn and an input field with the id #input. The following code snippet is functional: $('#input').on('input', function() { ...

Tips for programmatically adding together numerous input entries within a PHP while loop utilizing java-script on the onfocusout event

Currently, I am working on a method to determine the value of the following id: id="salenag<?php echo $a; ?>". This involves fetching multiple values from a database using PHP and then summing them up before injecting the total into an in ...

Is it a bug if we utilize AngularJS to retrieve data for <li><a href>?

Using AngularJs, I am able to retrieve data from a MySQL database for my navigation bar on an HTML5 page. However, there seems to be an issue with opening links in the sub menu. Below is a snippet of my code: <div id="header-wrapper" class="wrapper"> ...

What is the best way to display several components in a particular location within a parent component using react-native?

I am struggling to position multiple components within a parent component at a specific location determined by some calculations. The calculations for the vertical position seem accurate, but the components are not appearing where they should be. I have ex ...

Working with JSON data in AngularJS: A guide to loading data onto a scope variable

I am in the process of developing my personal website where I want to be able to update content easily without having to mess with the HTML code. My approach involves loading and updating a JSON file to achieve this, however, I am currently struggling with ...

What is the best way to close a popup window?

Is there a way to close my popup? function hidePopup(){ document.getElementById("popup-1").classList.remove("active"); } @import url('https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap'); .popup .overlay{ positio ...

Loop through the tabs array and display varying views based on conditionals

I am currently working on building tabs and tab panels iteratively to display information, but I am facing issues in getting the desired output. For each name in a list, I need to create a tab and a corresponding tab panel underneath it. For example, the ...

Leverage the retrieved JSON data from the database within an HTML template using the Play

Currently, I am facing a challenge with implementing a login feature in my project. I am struggling to figure out how to showcase the JSON string that is returned on the webpage. Below is a snippet of my code: Security.java: public Person webLogin(Perso ...

What are some ways I can troubleshoot my contact form?

As someone new to web design, I recently completed my very first site using a combination of HTML, CSS, and a touch of JavaScript. I managed to create a small contact form within the site, but now I'm wondering if there's a way to make it functio ...

Utilizing .html() to convert JSON data into HTML content

I have thoroughly commented the code below in my attempt to retrieve JSON data and pass it to the 'results' div in my HTML view. However, this process seems to return nothing, making it challenging to debug since no output can be displayed on the ...

"Vue.js and Node.js have been successfully installed, with their respective versions displayed. However, the applications are

kirti@kirti-Vostro-14-3468:~/flipbook-vue$ node --version v17.6.0 kirti@kirti-Vostro-14-3468:~/flipbook-vue$ vue --version @vue/cli 5.0.1 kirti@kirti-Vostro-14-3468:~/flipbook-vue$ npm run serve > <a href="/cdn-cgi/l/email-protection" class="__cf_em ...