How to use the Merge Sort Algorithm In Javascript
In this approach, we define functions to merge two sorted arrays and perform Merge Sort on a 1D array. Iterate through each row of the 2D array and apply Merge Sort, which recursively divides the array into halves until each half contains only one element, then merges them back together in sorted order. Repeat this process for each row in the 2D array.
Example: Implementation of Sort the 2D Array Across Rows Using the Merge Sort Algorithm
// Function to merge two sorted arrays
function merge(left, right) {
let result = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length &&
rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
result.push(left[leftIndex]);
leftIndex++;
} else {
result.push(right[rightIndex]);
rightIndex++;
}
}
return result.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex));
}
// Function to perform merge sort on a 1D array
function mergeSort(arr) {
if (arr.length <= 1) {
return arr;
}
const middle = Math.floor(arr.length / 2);
const left = arr.slice(0, middle);
const right = arr.slice(middle);
return merge(mergeSort(left), mergeSort(right));
}
// Function to sort a 2D array
// across rows using Merge Sort
function sort2DArrayAcrossRows(arr) {
// Iterate through each row of
// the array and apply Merge Sort
return arr.map(row => mergeSort(row));
}
// Example usage:
const array2D = [
[4, 2, 6, 1],
[9, 5, 3, 8],
[7, 1, 2, 0]
];
const sortedArray = sort2DArrayAcrossRows(array2D);
console.log(sortedArray);
Output
[ [ 1, 2, 4, 6 ], [ 3, 5, 8, 9 ], [ 0, 1, 2, 7 ] ]
JavaScript Program to Sort the 2D Array Across Rows
We will see how to sort the 2D Array across rows using a Javascript program. we can sort the 2D Array Across Rows in many ways including Bubble Sort Algorithm, Array.prototype.sort() method, Insertion Sort Algorithm, Using the Selection Sort Algorithm, and Merge Sort Algorithm.
Example:
Input:
[[8 5 7 2],
[7 3 0 1],
[8 5 3 2],
[9 4 2 1]]
Output:
[[2, 5, 7, 8], [0, 1, 3, 7], [2, 3, 5, 8], [1, 2, 4, 9]]
These are the following approaches:
Table of Content
- Using the Bubble Sort Algorithm
- Using the Array.prototype.sort() method
- Using the Insertion Sort Algorithm
- Using the Selection Sort Algorithm
- Using the Merge Sort Algorithm
Contact Us