Approach 2 : Using Map() method
In this approach, we calculates the minimum swaps required to sort an input array. It uses a Map to track element positions, then iterates through the array, swapping elements to their correct positions. The total swaps are counted, and the sorted array is logged. This approach ensures elements are in ascending order with the fewest swaps.
Example:
const arr = [9, 5, 8, 2, 1, 6, 3, 4, 7];
const elementToIndex = new Map();
for (const [index, value] of arr.entries()) {
elementToIndex.set(value, index);
}
let swaps = 0;
for (const [i, element] of arr.entries()) {
if (element !== i + 1) {
const correctElement = i + 1;
const currentElement = element;
// Swap the elements
[arr[i], arr[elementToIndex.get(correctElement)]] =
[correctElement, currentElement];
elementToIndex.set(
currentElement, elementToIndex.get(correctElement));
elementToIndex.set(correctElement, i);
swaps++;
}
}
console.log("Minimum swaps required:", swaps);
console.log("Sorted array:", arr);
Output
Minimum swaps required: 7 Sorted array: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Time Complexity: O(n) for iterating the array once.
Space Complexity: O(n) for using a Map data structure.
JavaScript Program to Find Minimum Number of Swaps to Sort Array
The minimum number of swaps to sort an array is the smallest quantity of element swaps needed to arrange the array in ascending or descending order. This minimizes the number of exchanges and is a key metric in sorting algorithms, as reducing swaps often improves efficiency and performance when organizing data structures.
Table of Content
- Approach 1: Using nested loop
- Approach 2 : Using Map() method
- Approach 3: Using Bubble Sort
- Approach 4: Compare the original array with a sorted copy
- Approach 5: Cycle Detection in Graph