Issue with array doesn't update when switching positions of elements

I encountered a strange issue while working on my visualizer for sorting algorithms. Everything was going smoothly until I reached the Selection Sort algorithm. The problem lies in the fact that the i value doesn't seem to change during each pass, causing the MINIMUM value to repeatedly swap based on the position of i. I conducted tests by changing the color of the block represented by the i index and it remained unchanged. This anomaly only occurs with the selection sort method, not with any other sorting methods.

If you're interested in exploring this issue further, feel free to check out my project on GitHub Pages. Simply use the left Navbar to select Selection Sort and observe the problem firsthand. Additionally, below is the code snippet for the swap function.

Github Pages --

Selection function

insert code snippet here

Swap function

insert code snippet here

Answer №1

I managed to resolve the issue by converting the Nodelist array obtained from .querySelectorAll into a regular array using .Arrayfrom(). With some research, I was able to easily figure out this step. Next, I had to determine how to update the array in each iteration, which turned out to be as straightforward as shifting one index to another.

The intriguing aspect of the solution was updating the Nodelist itself to ensure that all my CSS code remained functional (as it is a sorting visualizer). Surprisingly, the answer was quite simple. Even after transforming the Nodelist array into a standard array, I could still apply styles to it without altering the Nodelist array. This allowed me to maintain a separate array within the function for manipulation.

PS. The algorithm encountered significant issues in the previous snippet due to comparing two strings in the if statement (value1 and value2), resulting in errors. This was quickly resolved by wrapping my innerHTML code with the Number() function.

Selection

async function selectionSort() {
    let blocks = document.querySelectorAll('.block');
    let convertedBlocks = Array.from(blocks);
    let len = convertedBlocks.length;
    for (let i = 0; i < len; i++) {
        let min = i;
        for (let j = i + 1; j < len; j++) {
            convertedBlocks[j].style.backgroundColor = 'red';
            convertedBlocks[min].style.backgroundColor = 'green';
            convertedBlocks[i].style.backgroundColor = 'orange';
            await new Promise((resolve) =>
                setTimeout(() => {
                    resolve();
                }, frame_speed)
            );
            if (
                Number(convertedBlocks[min].childNodes[0].innerHTML) >
                Number(convertedBlocks[j].childNodes[0].innerHTML)
            ) {
                convertedBlocks[min].style.backgroundColor = '#58B7FF';
                min = j;
            }
            convertedBlocks[j].style.backgroundColor = '#58B7FF';
        }
        if (min !== i) {
            let tmp = convertedBlocks[i];
            convertedBlocks[i] = convertedBlocks[min];
            convertedBlocks[min] = tmp;
            await swap(convertedBlocks[i], convertedBlocks[min]);
        }
        convertedBlocks[min].style.backgroundColor = '#58B7FF';
        convertedBlocks[i].style.backgroundColor = '#58B7FF';
    }
}

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

What causes the error message "ng-model is undefined"?

Within my form, there are three angular-ui-bootstrap typehead elements <form> <div class="form-group"> <label for="fieldname" class="col-md-3 control-label">Name</label> <div class="col-md-6"> <input type="text ...

Guide to importing an AngularJS controller into an Express file (routes.js)

Currently, I am in the process of developing a restful service and my goal is to organize my callbacks within controllers in order to avoid cluttering my routes.js file. Previously, I had been using controller = require(path.to.controller); This enabled ...

Tips for leveraging stage 3 functionalities in TypeScript?

Array.prototype.at() is currently in the proposal stage 3. Even after adding "lib": ["ESNext"] to my tsconfig.json, I encountered the error: Property 'at' does not exist on type 'number[]'. Could you shed some light ...

"Using axios and async/await in VUE.JS to perform multiple asynchronous GET

Perhaps this is a somewhat basic inquiry, as I am still learning the ropes of vue.js and javascript. Please bear with me if my question is not well-articulated or if the solution is straightforward... I am facing an issue where I need to retrieve data from ...

What is the best way to serialize data from non-form elements and make it easily accessible through params[:model]?

I have developed a unique Sinatra application that leverages an external API to load data and exhibit it on a page. Utilizing Sinatra, the information is retrieved and stored in a temporary model instance (which is NOT saved) for seamless access to all its ...

Utilizing React Router: Combining MemoryRouter and Router for Dynamic Routing (leveraging memory for certain links while updating the URL for others)

While utilizing react-router-dom, I came across the helpful <MemoryRouter>. However, I am in need of having several routes that can read and write to/from the browser's URL. What is the best approach for implementing this functionality? Thank y ...

Tips for troubleshooting objects within an Angular template in an HTML file

When I'm creating a template, I embed some Angular code within my HTML elements: <button id="btnMainMenu" class="button button-icon fa fa-chevron-left header-icon" ng-if="(!CoursesVm.showcheckboxes || (CoursesVm.tabSelected == 'curren ...

Issue with Chart JS: Firefox is reporting that the 'Chart' is not defined

As a newcomer to Chart JS, I am currently utilizing it in Angular JS version 1.5.3 with Chart JS version 2.1.4. Below is the code snippet I am working with: var myChart = new Chart(ctx, { type: 'line', data: { labels: dates, datasets: [{ ...

Comparing front end automation between JavaScript and Java or Ruby

Could you provide some insights on why utilizing a JS framework like webdriverio is preferred for front end automation over using Selenium with popular languages like Java or Ruby? I understand that webdriverio and JS employ an asynchronous approach to fr ...

Library that supports Base64 encoding and decoding for both C and JavaScript environments

Are there any base 64 encoding and decoding libraries that are compatible with both C and JavaScript? Ideally, the library would have identical algorithms for both the encode and decode functions, allowing it to be used for desktop application clients (C++ ...

Determine the horizontal movement of x and z on a flat surface while accounting for

Using HammerJS, I am able to manipulate a 3D object within an augmented reality environment. Everything functions properly unless I physically move my phone (which serves as the camera)... const newTranslation = new THREE.Vector3(this._initTranslation.x ...

JavaScript code to prevent user from entering phone number

I operate a booking platform similar to AirBnB where users communicate with each other through messages on the site. My goal is to prevent users from sharing telephone numbers and email addresses within these messages. Currently, I am implementing a meth ...

The catch all route in Next.js seems to be malfunctioning when paired with the getStaticPaths function

Why is the Next.js catch all route not working as expected with the getStaticPaths function? The documentation states that I should be able to navigate to both t/a.cat and t/a.cat/a.id, but it only seems to work for the latter. What could be causing this ...

Struggling to populate a nested array in a dropdown using AngularJS

I am currently working on populating JSON data into a dropdown list, specifically focusing on main category, sub category and sub sub category. Successfully managed to populate the main category and sub category, but facing challenges with populating subsu ...

Trouble with AJAX GET request functionality

I am new to AJAX and attempting to make my first AJAX call. Here is the code I have so far: $.get( "validate.php", { 'userinput':'x'}, function(response) { if( response.status ) alert( "Matches found" ); else alert( "No matches ...

guide to importing svg file with absolute path

I have been attempting to load SVG files from my LocalDrive using an absolute path. Despite successfully achieving this with a relative path, the same method does not work when utilizing an absolute path. <script> $(document).ready(functio ...

Error message "Unable to access property 'rotation' of an object that does not exist - Three.js"

I'm currently facing an issue where my code is executing as expected, but there are two errors popping up in the console saying "Cannot read property 'rotation' of undefined". It's puzzling because both variables are defined globally. I ...

MongoDB failing to store model information

As I dive into practicing with APIs to hone my skills in creating models and routes, I find myself stuck on getting my initial route to successfully save data to my MongoDB database. When testing with Postman, I encounter the following error: { "message" ...

What is the best way to ensure a specific section of a website remains visible and fixed at the bottom of the page

I want to set up a simple toolbar with divs and uls containing both anchors and tabs. The position of the toolbar needs to be fixed at the bottom of the page. <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional/ ...

The "click" event is only effective for a single use

I am looking for a way to trigger the click event more than once in my project. I attempted using "live" but it didn't work as expected. There are 2 other similar scripts in this Django project. If you have any suggestions on improving this project, p ...