How to use the Selection Sort Algorithm In Javascript
In this approach, we use selection sort to repeatedly selects the minimum element from the unsorted portion of the array and places it at the beginning and by continuing this process until the entire row is sorted. We repeat this process for each row to sort the 2D array.
Example: Implementation of Sort the 2D Array Across Rows using the selection sort algorithm
// Function to sort a 2D array
// across rows using Selection Sort
function sort2DArrayAcrossRows(arr) {
// Iterate through each row of the array
for (let i = 0; i < arr.length; i++) {
// Apply Selection Sort to the current row
for (let j = 0; j < arr[i].length - 1; j++) {
let minIndex = j;
for (let k = j + 1; k < arr[i].length; k++) {
if (arr[i][k] < arr[i][minIndex]) {
minIndex = k;
}
}
if (minIndex !== j) {
let temp = arr[i][j];
arr[i][j] = arr[i][minIndex];
arr[i][minIndex] = temp;
}
}
}
return arr;
}
// 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