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

Update object properties in Angular controller dynamically

Take a look at my simple plunker Within the code, I am attempting to link a scope variable to an object property. $scope.name = 'World'; var obj = { "name":$scope.name } $scope.$watch('name', function(){ console.log(obj["name"]); ...

What is the most effective way to reduce the number of http requests caused by onChange events in Material UI Slider?

Is there a way to optimize my request handling? In my React project, I am currently utilizing Material UI's slider. With the onChange property, I am making HTTP POST requests whenever the slider is moved. Here is a snippet of the code: <Slider ...

Update the parent element's class style within a targeted div media query

I am facing a challenge where I want the width of my .container element to be 100% when the screen size reaches 900px. The issue is that I have used .container on multiple pages and only wish to change its appearance within the #sub-top div. The terminolo ...

What could be causing the div to not respond to ngAnimate?

Recently, I encountered an issue with adding animations to a list of <div>'s in my webapp. After incorporating ngAnimate into the app.js file and including ng-animate="'animate'" in the <div>, I was disappointed to find that the ...

Ways to reload an independent page in order to access PHP session variables:

Starting off, I want to mention that my approach may not be the most efficient. As a novice in JavaScript and PHP, I am aware that there are better and simpler ways to achieve what I'm attempting. The issue seems to be related to session variables an ...

javascript has a funny way of saying "this is not equal to this" (well,

Sample 1 var Animal = function () { var animal = this; this.makeSound = function() { alert(animal.sound); } } var dog = new Animal(); dog.sound = 'woof'; dog.makeSound(); Sample 2 var Animal = function () { this.makeSound = ...

Failed Cross-Origin Request Sharing in AngularJS 1.4

I'm currently working with AngularJS version 1.4.3 and here is the code snippet I am using: angular .module('app', []) .run(run); function run($http) { a = $http({ method: "GET", url: 'http://127.0.0 ...

Retrieving the Short Date Format from the user's device or browser within a React application

Currently, I am in the process of utilizing reactjs along with material UI datepicker. My objective is to transmit the short date format to the datepicker component, such as format="MM/dd/yyyy". In addition, I wish to employ the pre-existing date ...

Alert event in JavaScript navigating between different pages

My website features two dynamic php pages: customer invoices and customer management. One common request from my users is the ability to swiftly add a new customer directly from the customer invoices page. Instead of cluttering the customer invoices page ...

Retrieving custom data attributes from slides within a slick carousel

After the recent Slick carousel update to version 1.4, there have been changes in how data attributes are accessed from the current slide. The previous method that was working fine is as follows: onAfterChange: function(slide, index) { $('.projec ...

Chrome has some issues with resizing the SVG Pattern element

Utilizing inline svgs, I have a svg circle filled with a pattern that should cover 100% of the container size. However, when the parent element is resized via JavaScript, the pattern no longer reflects the 100% width and height as expected. This issue seem ...

Issue with window resize directive not functioning as expected

I have recently crafted a personalized directive in AngularJS. Here's the code snippet: var esscom = angular.module('esscom',['ngMaterial' ,'ngMessages','ui.bootstrap','ui.router']); esscom.directiv ...

Node and browser compatible JavaScript logging library for effective logging experience across platforms

Our team is utilizing Visionmedias debug library, as it seamlessly functions on both browsers and Node.js environments. We are in search of a more reliable alternative to debug that offers the same level of functionality (error, warn, info, etc) for both ...

Error: 'require' is not recognized as a valid command - Node.js

I recently attempted to integrate the d3-gauge plugin into a basic node.js/express server. Following the default directory structure generated by Express, I organized the files from the 'example' folder as follows: . ├── app.js ├── b ...

Unlocking the Secret: How to Bind a Global Touch Event Handler in Angular 4 to Prevent iOS Safari Page Drag

The issue at hand is that within my Angular 4 application, there is a D3.js chart that relies on user touch input for dragging a needle to a specific value. The drag functionality is triggered by 'touchstart', while the registration of the final ...

Confirm that the method has been called by utilizing the AVA testing framework

As I work on creating a unit test for my React component using tools like Ava and Enzyme, I encounter an issue. My goal is to create a simple unit test that checks if a certain method has been called. The test should pass if the method has indeed been call ...

Using Selenium to determine the quantity of elements that have a similar class present

Here is the test code I am using: it('count elements by class', async t => { let count = await driver.findElements(By.css('my-questions-class')).then(v => v.length); assert.equal(count, 3); // The count should b ...

Electron and React: Alert - Exceeded MaxListenersWarning: Potential memory leak detected in EventEmitter. [EventEmitter] has 21 updateDeviceList listeners added to it

I've been tirelessly searching to understand the root cause of this issue, and I believe I'm getting closer to unraveling the mystery. My method involves using USB detection to track the connection of USB devices: usbDetect.on('add', () ...

Triggering Various Button Click Actions with Jquery Event Handlers

Is it possible to attach several Button Click events to the same function like the example below? $(document).on("click", "#btn1 #btn2 #btn3", callbackFunction); ...

jQuery AJAX call failing to return to page

Currently, my form is set up to upload multiple text fields and a file to a PHP script for saving. The script successfully saves the file and text fields to an SQL database. At the end of the PHP script, I have the following code snippet: ('state&apo ...