A step-by-step guide to implementing bubble sort for sorting a 2D array in JavaScript

Here's a function that requires modification to work with a 2D array:

function sortTwoDimensionalArray(arr) {
  var numRows = arr.length;
  for (var i = 0; i < numRows; i++) { 
    for (var j = 0; j < (numRows - i - 1); j++) { 
      if(arr[j][0] > arr[j+1][0]) {
        var temp = arr[j];  
        arr[j] = arr[j+1]; 
        arr[j+1] = temp; 
      }
     }
  }        
}

This function takes a 2D array such as the example below, and sorts it based on the values in the first column:

[ [39, 43, 32], [300, 44, 1] ]

After sorting, it would return:

[ [1, 32, 39], [43, 44, 300] ]

Remember to adjust the function logic based on your specific requirements.

Answer №1

To address the specific scenario you provided, one possible solution is to merge the two sub-arrays, sort the merged array, and then split it back into two separate sub-arrays.

function bubbleSort(items) {
  var length = items.length;
  for (var i = 0; i < length; i++) { 
    for (var j = 0; j < (length - i - 1); j++) { 
      if(items[j] > items[j+1]) {
        var tmp = items[j];  
        items[j] = items[j+1]; 
        items[j+1] = tmp; 
        }
     }
  }
  return items;
}

var a = [ [39, 43, 32], [300, 44, 1] ];
var a2 = bubbleSort(a[0].concat(a[1]));
a[0] = a2.slice(0,3);
a[1] = a2.slice(3,6);

If the array contains many elements, this approach may become slow. Additionally, if the sub-arrays have varying lengths, a different strategy would be needed. In such cases, preprocessing the array to store individual lengths in a separate array before sorting and merging could offer a more robust solution.

Answer №2

To efficiently handle the nested array, one effective approach is to deconstruct the nested structure into a flat array, arrange it in ascending order, and then reconstruct the sorted values back into the original nested array:

function customBubbleSort(items) {
  var flatArray = [];
  for (var i = 0; i < items.length; i++) { 
    flatArray = flatArray.concat(items[i]);
  }
  for (var i = 0; i < flatArray.length; i++) { 
    for (var j = 0; j < (flatArray.length - i - 1); j++) { 
      if(flatArray[j] > flatArray[j+1]) {
        var temp = flatArray[j];  
        flatArray[j] = flatArray[j+1]; 
        flatArray[j+1] = temp; 
      }
    }
  }
  for (var i = items.length-1; i>=0; i--) { 
    items[i] = flatArray.slice(-items[i].length);
    flatArray.length -= items[i].length;
  }
  return items;
}

result = customBubbleSort([ [39, 43, 32], [300, 44, 1] ]);
console.log(result);

Generated Output:

[ [1, 32, 39], [43, 44, 300] ]

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

Changing the background-color with CSS class toggling

I'm having an issue with an element that is supposed to change its background color from "lightGreen" to "red" upon hovering. However, even though the class is being added properly, the color remains lightGreen. It's worth noting that the elemen ...

React project automatically refreshing when local server generates new files

I have developed a tool for developers that allows them to retrieve device data from a database for a specific time period, generate plots using matplotlib, save the plots locally, and display them on a webpage. The frontend is built using create-react-app ...

Not all of the data is being retrieved

A form on the page contains two dropdown lists for selecting blood type and city, along with a button. When the button is clicked, information about donors matching the selected blood type and city will be displayed below the form. The postgres database co ...

Unexpected Error Occurs When Attempting to Update jQuery Version with AJAX Post Request

My challenge involves working with multiple radio elements, each with different names and values. When a radio button is clicked, I need to send the data to the server using AJAX. Here is my current AJAX method: $("input[type=radio]").click(function() { ...

How can we ensure that an enum is accessible throughout the entire meanjs stack?

Currently, I am exploring the meanjs technology stack and facing a challenge in creating a centralized enum array that can be accessed throughout the project, from MongoDB to Angular. Can anyone suggest a smart solution for accomplishing this task? ...

How can I duplicate an array in C or C++?

In my exploration of Java, I discovered the function System.arraycopy(); for copying arrays. This led me to wonder if C or C++ have a similar function for array duplication. Despite my search efforts, all I could find were implementations involving for l ...

Prevent users from viewing or editing profiles of other users

I need to enhance the security of my application by restricting users from accessing profiles of other users. route.js router.get('/currentUser/:username', userAuth, (req, res) => { User.findOne({ username: req.params.username }).the ...

Developed a query, seeking information for populating a dropdown menu

I am currently in the process of editing a webpage that utilizes both PHP and HTML. Essentially, I have a dynamic list of items being generated where the number of values can vary based on the row length. Next to each item in the list, there is a "delete ...

Display the initial three image components on the HTML webpage, then simply click on the "load more" button to reveal the subsequent two elements

I've created a div with the id #myList, which contains 8 sub-divs each with an image. My goal is to initially load the first 3 images and then have the ability to load more when clicking on load more. I attempted to follow this jsfiddle example Bel ...

Determining the nearest upcoming date from a JSON dataset

Looking to find the nearest date to today from the array "dates". For example, if today is 2011-09-10 -> the next closest date from the JSON file is "2012-12-20" -> $('div').append('date1: ' + dates.date1); For example 2, if tod ...

Ways to incorporate a dynamic HTML form that allows for input elements to be added both horizontally and vertically while maintaining connected lines

Looking to design a form that showcases HTML elements in both vertical and horizontal positions, with lines connecting them as seen in this example: https://i.sstatic.net/jB12f.png. Can anyone offer guidance on how to achieve this? Thanks! ...

How to automatically update a hidden input field using Typeahead.js and key values from a JSON data source

On one of my pages, I have successfully implemented a typeahead feature that retrieves data from a remote URL in the form of a JSON string like this: [{"id":"1","name":"Ben"},{"id":"2","name":"Josh"}]. My goal is to update a hidden field with the correspo ...

Tips for transforming a magenta.js note sequence into a MIDI file

I need to convert a note sequence using Magenta.js into a midi file and generate a url for users to download. The goal is to use this url in a midi-player/visualizer. // Creating a Magenta note sequence generateMelody(sendedNotes, 0.7, document.getElementB ...

The jQuery ajax function functions flawlessly on a local environment, but encounters issues when used on a

After spending the entire day researching this issue, it appears to be a common problem without a solution in sight. The challenge I am facing involves using jquery's $.ajax() function to update database values through a service call. While it works ...

Refresh page upon clicking the same state link in AngularJS using ui.router

Just received an interesting request from our QA team that seems a bit out there. Let's dive in: imagine you are already on the 'about' state/page within an angular-based app, and when you click on the 'about' state URL again from ...

The Material UI React radio buttons have the ability to modify the value of previous buttons

I'm facing an issue with my Material UI React Stepper Component that contains a group of radio buttons. The problem is that changing the radio button in one step affects the selected value in previous and future steps. I've experimented with diff ...

Creating chained fetch API calls with dependencies in Next.js

I am a novice who is delving into the world of API calls. My goal is to utilize a bible api to retrieve all books, followed by making another call to the same api with a specific book number in order to fetch all chapters for that particular book. After ...

Exploring the world of C programming with the concept of passing arrays to functions

Could you please explain the reasoning behind initializing int count, biggest = -12000;? I am struggling to understand why it needs to be set to -12000 specifically. If I change it to biggest = 10000, the code still compiles just fine. I'm new to lear ...

Steps to creating an Ajax JQuery in WordPress with promises

Currently, I am in the process of developing a custom Wordpress Google Maps plugin. This plugin fetches locations from a database using Ajax and returns an XML file that is then handled by a Javascript script to display them on a Google Map. Everything is ...

Tips to avoid multiple HTTP requests being sent simultaneously

I have a collection of objects that requires triggering asynchronous requests for each object. However, I want to limit the number of simultaneous requests running at once. Additionally, it would be beneficial to have a single point of synchronization afte ...