What is causing the list-sorter to malfunction?

This website crashes when executed:

<head>
<script>
    var numbersList = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1];
    var orderedList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
    var count = 0;

    while (numbersList !== orderedList) {
        if (numbersList[count] > numbersList[count + 1]) {
            var lowNum = numbersList[count + 1];
            var highNum = numbersList[count];
            numbersList[count] = lowNum;
            numbersList[count + 1] = highNum;
        }
        if (count === 19) {
            count = 0;
        } else {
            count = count + 1;
        }
    }
</script>
</head>

</html>

How can I fix this issue?

Based on my understanding, the logic is correct as per my intention. This is simply a recreational experiment.

After additional development, the comparison problem has been resolved:

<!doctype html>
<html>
<head>
    <script>
    var passes = 0;
    var swaps = 0;
    var numList = [25, 21, 4, 23, 32, 2, 40, 8, 27, 9, 29, 33, 31, 14, 12, 16, 35, 18, 37, 20, 39, 19, 38, 17, 36, 15, 34, 13, 6, 11, 30, 10, 28, 7, 26, 5, 1, 3, 22, 24];
    var index = 0;
    var swappedNum = 0;
    var inOrder = 0;

    while (inOrder !== 1) {
        if (numList[index] > numList[index + 1]) {
            var lowerVal = numList[index + 1];
            var higherVal = numList[index];
            numList[index] = lowerVal;
            numList[index + 1] = higherVal;
            swappedNum = 1;
            swaps = swaps + 1;
        }
        if (index === numList.length - 1) {
            if (swappedNum === 0) {
                inOrder = 1;
            }
            swappedNum = 0;
            index = 0;
        } else {
            index = index + 1;
        }
        passes = passes + 1;
    }
    alert("Number List: " + numList);
    alert("Passes: " + passes + ", Swaps: " + swaps);
</script>

(Similar to how the "cooky monster" suggests)

Answer №1

When comparing array objects in JavaScript, keep in mind that they will never be considered the same object even if their contents are identical. This is because JavaScript does not compare values when using comparison operators on objects like arrays; instead, it checks if they are identical objects. To quickly compare two arrays without diving into serialization, you can try this approach:

<head>
<script>
var list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1];
var listOrdered = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
var loopCount = 0;

while (JSON.stringify(list) !== JSON.stringify(listOrdered)) {
    if (list[loopCount] > list[loopCount + 1]) {
        var lower = list[loopCount + 1];
        var higher = list[loopCount];
        list[loopCount] = lower;
        list[loopCount + 1] = higher;
    }
    if (loopCount === 19) {
        loopCount = 0;
    } else {
        loopCount = loopCount + 1;
    }
}
alert(JSON.stringify(list)) // [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
</script></head></html>

If you need to support older browsers that do not have JSON.stringify by default, you can use a polyfill like https://github.com/douglascrockford/JSON-js/blob/master/json2.js

Answer №2

Instead of utilizing a comparison method, it would be more efficient to implement a flag system to indicate whether values were swapped during an iteration. If a swap occurred, the counter is reset to 0 and the flag is reset. If no swaps were made, then the sorting process is complete.

var list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1];
var loopCount = 0;
var swapped;

while (true) {
    if (list[loopCount] > list[loopCount + 1]) {
        var lower = list[loopCount + 1];
        var higher = list[loopCount];
        list[loopCount] = lower;
        list[loopCount + 1] = higher;
        swapped = true;     // Flag showing a swap occurred.
    }
    if (loopCount === 19) { 
        if (swapped) {    
            swapped = false;
            loopCount = 0;
        } else
            break; 
    } else {
        loopCount = loopCount + 1;
    }
}

This approach will outperform array comparisons for sorting operations.

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

Introducing React JSX via a nifty bookmarklet

Looking to convert code found in an HTML file into a bookmarklet? Here's the code snippets involved: <script src="JSXTransformer-0.13.3.js"></script> <script src="react-0.13.3.js"></script> <script type="text/jsx;harmony=tr ...

Pytest is not able to locate any elements on the webpage, yet the same elements can be easily found using the console

When using CSS or XPath in the console (F12), I am able to locate the element on the page. $$("span.menu-item[data-vars-category-name='Most Popular']") However, when trying to find the same elements with Selenium (pytest) using: driver.find_el ...

Use PipeTransform to apply multiple filters simultaneously

Is it possible to apply multiple filters with PipeTransform? I attempted the following: posts; postss; transform(items: any[]): any[] { if (items && items.length) this.posts = items.filter(it => it.library = it.library ...

The function is failing to return a false value

I have encountered a problem with my code - it works fine in Chrome but not in IE or Firefox. I've tried using return false; and event.preventDefault() but they don't seem to be effective in Firefox. The issue arises when the button grabs informa ...

Incorporate VLC player into a webpage without any visible control options

Is there a way to embed a flash video in a webpage without showing any controls? I managed to embed a flash video using VLC with the following code: <embed src="img/Wildlife.wmv" height="480" width="640"> However, I want the video to play without ...

What is the best way to add randomness to the background colors of mapped elements?

I am looking for a way to randomly change the background color of each element However, when I try to implement it in the code below, the background color ends up being transparent: { modules.map((module, index) => ( <div className='carou ...

Incorporating imports disrupts the script configuration in Nuxtjs 3

Issues arise when utilizing the import statement within the context of <script setup>, causing subsequent code to malfunction. After installing the @heroicons package and importing it as a component in the <template>, all code below the import ...

Post response not being received by Node.js Express static file on the client side

Greetings all, I'm currently delving into mobile development and seeking to expand my knowledge of the Node.js runtime. As part of my learning process, I have a simple client-side "app" written in JavaScript that I am attempting to integrate with a No ...

What is the best way to deactivate the first two columns of the header in Vue?

I am attempting to deactivate the draggable function for the first 2 columns. I have tried using options in the draggable plugin. :options="{disabled : 'Subject'}" However, this disables the draggable functionality for all headers. < ...

Tips for resizing the MUI-card on a smaller screen

Is there a way to adjust the width of the card on small screen sizes? It appears too small. You can view my recreation on codesandbox here: https://codesandbox.io/s/nameless-darkness-d8tsq9?file=/demo.js The width seems inadequate for this particular scr ...

Selecting the optimal data structure: weighing the benefits of using boolean check versus array .include (balancing performance and redundancy

My objects can have one or more properties assigned, with a total of 5 different properties in my case. To illustrate this, let's use a simple movie example where each movie can be assigned from 5 different genres. I have come up with two methods to ...

Issues with clickable links within a table cell

I am facing an issue with a table where rows <tr> are generated dynamically by a PHP loop. I have transformed the entire row into a link, but the problem arises when there is an <input type="checkbox"> within the row. Whenever I check the check ...

"After executing a loop in JavaScript using jquery.ajax, the success function does not perform

Having trouble passing values from a PHP file to another function in Javascript. Even after a successful FOR LOOP, nothing seems to work within the SUCCESS block. Any suggestions? url1 = 'http://localhost:81/Dashboard/admin/inc/dashboard.php'; $ ...

What is the best way to showcase information retrieved using the getDocs function from Firebase Firestore?

Hello! I am currently exploring the world of Firestore and facing a challenge. My goal is to retrieve a data object from Firestore, set it as state, and then display it on my application: Below are the imports that I have utilized for this task (please ig ...

What could be the reason my div is not being hidden in jQuery?

Creating a quiz layout for school is my current project, and I'm just getting started. My goal is to have the questions disappear once the 'next question' button is clicked. The issue arises after the second question because instead of the ...

Divide the array of words into segments based on the maximum character limit

I am looking for a way to divide an array of words into chunks based on a maximum number of characters: const maxChar = 50 const arrOfWords =['Emma','Woodhouse,','handsome,','clever,','and','rich,&apo ...

How to Refine Database Queries in Laravel Without Using Conditional Statements

I am currently facing the challenge of filtering users in my database using numerous if / elseif statements, and I'm on the lookout for a more efficient method. At present, I find myself writing if statements for every possible query based on the foll ...

Tips for activating an HTML input field using Javascript

I am currently using localStorage to store a string input by the user as a title, which will be saved for future visits. I would like to implement a button that allows the user to delete the displayed text (from localstorage) and enables the input field fo ...

I found myself pondering the significance of the {blogs: blogs} in my code

app.get("/articles", function(req, res){ Article.find({}, function(err, articles){ if(err){ console.log("an error occurred!!!"); }else{ res.render("homepage", `{articles: articles}`); } }); I created this c ...

Prevent automatic scrolling to anchors when using router.push() in Next.js

When using the latest version 10.2 of next, every time a URL with a hash is pushed to the router, next.js automatically jumps to the anchor element. import {useRouter} from 'next/router' router.push('/contact#about-us'); This behavior ...