Open In App

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.

Approach 1: Using nested loop

In this approach, we use loops with the help of the function swapsToSort, which calculates the minimum number of swaps needed to sort an array. It uses a loop to swap elements to their correct positions until the array is sorted, counting swaps. The sorted array and swap count are then printed.

Example: in this example, we are following the above-explained approach.

function swapsToSort(arr) {
    const n = arr.length;
    let swaps = 0;

    for (let i = 0; i < n; i++) {
        while (arr[i] !== i + 1) {
            const correctIndex = arr[i] - 1;
            [arr[i], arr[correctIndex]] = [arr[correctIndex], arr[i]];
            swaps++;
        }
    }

    return swaps;
}

const arr = [4, 3, 1, 2];
const result = swapsToSort(arr);
console.log("Minimum swaps required:", result);
console.log("Sorted array:", arr);

Output
Minimum swaps required: 3
Sorted array: [ 1, 2, 3, 4 ]

Time Complexity: O(n^2) due to nested loops for swapping elements in the array.

Space Complexity: O(1) as it uses constant extra space regardless of input size.

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.

Approach 3: Using Bubble Sort

In the Bubble Sort approach to find the minimum number of swaps, perform the bubble sort algorithm on the array while counting the number of swaps needed. The total swaps performed represent the minimum number of swaps required to sort the array.

Example: In this example minSwaps() function takes an array arr as input and returns the minimum number of swaps needed to sort the array using the Bubble Sort algorithm.

function minSwaps(arr) {
    const n = arr.length;
    let swaps = 0;

    for (let i = 0; i < n - 1; i++) {
        for (let j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap arr[j] and arr[j + 1]
                let temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swaps++;
            }
        }
    }

    return swaps;
}

const array = [4, 3, 2, 1];
console.log("Minimum number of swaps:", minSwaps(array)); 

Output
Minimum number of swaps: 6

Time Complexity: O(n^2) for iterating over the array with nested loops.

Space Complexity: O(1) for using a constant amount of extra space.

Approach 4: Compare the original array with a sorted copy

In this approach, we finds the minimum number of swaps needed to sort an array. It uses a sorted copy to compare elements, a swap function to rearrange them, and an indexOf function to find the correct position of elements. The final sorted array is displayed.

Example: In this example The function minSwaps iterates through the array, comparing it with the sorted version. Swaps are performed to sort the array, and the number of swaps required is returned.

function minSwaps(arr, N) {
    let ans = 0;
    let temp = [...arr];
    temp.sort((a, b) => a - b);
    for (const [i, element] of arr.entries()) {
        if (element !== temp[i]) {
            ans++;
            const j = indexOf(arr, temp[i]);
            swap(arr, i, j);
            
        }
    }
    return ans;
}

function swap(arr, i, j) {
    let temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

function indexOf(arr, ele) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === ele) {
            return i;
        }
    }
    return -1;
}

let arr1 = [9, 5, 8, 2, 1, 6, 3, 4, 7];
let result = arr1.length;
console.log(
    "Minimum swaps required:", minSwaps(arr1, result));
console.log("Sorted Array:", arr1);

Output
Minimum swaps required: 7
Sorted Array: [
  1, 2, 3, 4, 5,
  6, 7, 8, 9
]

Time Complexity: O(n^2) due to nested loops for element swaps.

Space Complexity: O(1) as the function uses minimal extra memory.

Article Tags :