JavaScript sorting code fails to properly sort numbers

Here is a code snippet that aims to convert a string into an array of numbers and then sort them in descending order. The objective is to find an alternative to the sort() method.

However, there seems to be an issue with the current implementation. When the number 7 is placed in the first half of the array (as shown in the example), the code malfunctions. Interestingly, if 7 is swapped with a number larger than the last one (as done with 22 in the example), the code works correctly.

The goal is to ensure that the code works properly regardless of the positioning of the numbers.

var row = '92 43 7 119 51 22';
var row = row.split(' ');
var column = row.map(Number);

function arrangeNum(column) {
    for (var i = 0; i <= column.length - 1; i++) {
        for (var j = column.length - i; j >= 0; j--) {
            if (column[j] > column[j - 1]) {
                var temp = column[j];
                column[j] = column[j - 1];
                column[j - 1] = temp;
            }
        }
    }
    return column;
}

console.log(arrangeNum(column));

Answer №1

There seems to be an issue with the code. When 7 is placed in the first half of the array (as shown in the example), the code malfunctions.

The problem lies in the initialization of the second-for-loop variable j

To fix this, update the code snippet as follows:

for (var j = column.length - 1; j >= i; j--) { 

It's important to note that j starts at column.length - 1 but can only go as low as i

Check out the demo below

function arrangeNum(column) {
  for (var i = 0; i <= column.length - 1; i++) {
    for (var j = column.length - 1; j >= i; j--) {
      if (column[j] > column[j - 1]) {
        [column[j], column[j - 1]] = [column[j - 1], column[j]];
      }
    }
  }
  return column;
}

console.log( arrangeNum( '92 43 7 119 51 22'.split( /\s+/ ).map( Number ) ) );

Answer №2

It seems like the issue you're facing stems from an incorrect implementation of the bubble sort algorithm.

The line

var j = column.length - i; j >= 0; j--
is causing the algorithm to ignore elements starting from the right side of the array. Since the algorithm is for descending order, it should actually be ignoring elements from the left side, like this:
var j = column.length - 1; j >= i; j--
.

I've included some console logs to illustrate this below: https://i.sstatic.net/HJQiR.png

As highlighted in yellow, your algorithm skips the first element in the next loop.

Below is my corrected version which addresses some other minor issues as well:

for (var i = 1; i <= column.length; i++) {
        for (var j = column.length - i; j >= 0; j--) {
            console.log({i,j}, column.map((v,idx) => (idx===j) || (idx===j-1) ? `[${v}]` : v ).join(' '))
            if (column[j] > column[j - 1]) {
                var temp = column[j];
                column[j] = column[j - 1];
                column[j - 1] = temp;
                console.log({i,j}, '  ',column.map((v,idx) => (idx===j) || (idx===j-1) ? `[[${v}]]` : v ).join(' '))
            }
        }
    }

Answer №3

To correct the issue, it is necessary to modify the sequence of commands in the j loop. Begin the loop from 0 up to column.length - 1

var row = '92 43 7 119 51 22';
var row  = row.split(' ')
 var column = row.map(Number);
function arrangeNum(column) {
  for (var i = 0; i <= column.length - 1; i++) {
    for (var j = 0; j <= column.length - i; j++) { // Adjust this part
      console.log(column)
       if (column[j] > column[j - 1]) {
       var temp = column[j];
       column[j] = column[j - 1];
       column[j - 1] = temp;
    }
  }
}

return column;
}

console.log(arrangeNum(column))

Answer №4

Here is a modified code snippet that should work as expected:

 var row = '92 43 7 119 51 22';
 var row = row.split(' ');
 var column = row.map(Number);
 function arrangeNum(column) {
  for (var i = 0; i <= column.length - 1; i++) {
    for (var j = column.length - 1; j >= i; j--) {// the modification is below
        if (column[j] > column[j - 1]) {
          var temp = column[j];
          column[j] = column[j - 1];
          column[j - 1] = temp;
        }
     }
  }
   return column;
}

console.log(arrangeNum(column));

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

The ng-show directive is failing to update properly after changes are made to the scope values

I'm experiencing some issues with the ng-show method. I have set it up like this: Even though the username string length is checked, the ng-show method doesn't seem to hide/show the extra text until after another keystroke. How can I make it upd ...

React is struggling to dynamically update text content using button click events

As a beginner in the world of React, Nodejs, and JavaScript, I am exploring onClick events to dynamically change text by clicking buttons. In my practice project, I have an input type="checkbox" that toggles the text between bold and normal style ...

Is there a way for me to change a string into an array?

I have a question regarding string conversion. Here is a snippet of code from a CodeIgniter controller: function getUsersFromProjects(){ $projectID = $_POST['projectID']; $data = $this->tasks->getUserIdFromProjects($projectID); ...

Chrome browser experiencing a disappearing vertical scroll bar issue on a Bootstrap Tab

<div class="tabs-wrap left relative nomargin" id="tabs"> <ul class="nav ultab" id="fram"> <li class="active"><a href="#history" data-toggle="tab" id="history1" >History< ...

Angular - What causes variables to lose data after component changes?

Having an issue with two components - one creating and changing an array, and the other getting the array. The problem is that when retrieving the array in the second component, it only shows the default empty data. Code for array creation: export cla ...

Controller method remains inaccessible despite multiple attempts with Javascript ajax Get call

I've tried numerous solutions for this issue, but I'm still unable to make it work. My goal is to invoke a controller method that accepts a parameter and returns a string based on that parameter. Despite using an ajax GET request, the outcome is ...

Secrets to concealing a Material UI column based on specific conditions?

Recently, I encountered a challenge with my MUI datagrid where I needed to hide a column based on a specific role. Below is the code snippet: const hideColumn = () => { const globalAdmin = auth.verifyRole(Roles.Admin); if(!globalAdmin){ ...

Encountering the Extjs 3.4 error ERR_UNKNOWN_URL_SCHEME while trying to access a legitimate JSON

Using Extjs 3.4, I am working on a simple ajax request: Ext.Ajax.request({ url: "localhost:3000/offers.json", success: function(response, opts) { var obj = Ext.decode(response.responseText); console.dir(obj); }, failure: funct ...

What is the best way to create a delay so that it only appears after 16 seconds have elapsed?

Is there a way to delay the appearance of the sliding box until 16 seconds have passed? <script type="text/javascript"> $(function() { $(window).scroll(function(){ var distanceTop = $('#last').offset().top - $(window).height(); ...

By employing the $watch method, the table disappears from the div element

I've integrated the isteven-multi-select directive for my multi-select dropdown functionality. By providing it with a list of thingsList, it generates a corresponding checkedList as I make selections. Initially, I used a button to confirm the selecti ...

What repercussions come from failing to implement an event handler for 'data' events in post requests?

If you take a look at the response provided by Casey Chu (posted on Nov30'10) in this particular question: How do you extract POST data in Node.js? You'll find that he is handling 'data' events to assemble the request body. The code sn ...

In the world of programming, what sets a pointer to pointer apart from a pointer to array?

When I type the following code: char array[] = "some text"; char **ptr = &array; printf("%s\n",*ptr); No output is printed and a warning message appears: warning: initialization from incompatible pointer type [enabled by default] However, if I ...

Tips for effectively overlaying one container on top of another in a responsive manner

There are a pair of containers. The main container functions as the parent, while the child container acts as a tag to categorize the content. The objective is to position the tag container at the top right corner of the main content container, slightly of ...

The require() function is not functioning properly, even after I tried switching the type from module to common. As a newcomer to this, there may be something essential that I

Despite changing the type from module to common, I am still unable to get require() to work. As a newcomer to this, there may be something I'm overlooking that I can't quite pinpoint. I attempted const express = require('express'); but ...

Comparing Embedded and Linked JS/CSS

In my experience, I understand the advantages of using linked CSS over embedded and inline styles for better maintainability and modularity. However, I have come across information suggesting that in certain mobile web development applications, it may be m ...

Ensure that all links are opened in a new tab

When including _blank in the a href URL, my website contains various elements like iframes and ads from Adsense, Taboola,, etc. Currently, when a user clicks on an iframe or ad, it opens in the same window. Is there a way to ensure that all URLs (includin ...

"The issue of segmentation fault occurs when attempting to access array size in C programming

Hey, I encountered a strange segmentation fault from the following code: int main(void){ int array1[10000000]; int n = sizeof(array1); printf("%d \n", n ); return 0; } However, when I make a small change to the code like so: int array ...

Utilizing Angularfire OAuth for Facebook authentication in login strategy

After successfully implementing the code below in the loginCtrl controller and login.html, I encountered some issues with setting up the workflow correctly. My goal is to achieve something like this: //check if the current $scope has authData //if so red ...

What is the significance of utilizing response.json() for accessing JSON objects on both the server and client sides?

Just starting out with the MEAN stack, I've included my API code below where I'm using res.json(random) to send a random password. module.exports.changePass = function (req, res) { console.log(req.body.email) db.user.find({ where: { name: ...

Using Vue.js to process JSON data

My issue lies within this JSON data. I am trying to consume only the first element of the array using Vue.js 2 in order to display it. I was able to achieve this successfully using the console, but not with Vue.js. This line of code in the console works: ...