JavaScript Program to Find Minimum Number of Swaps to Sort Array
Last Updated :
17 Jul, 2024
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.
JavaScript
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);
OutputMinimum 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:
JavaScript
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);
OutputMinimum 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.
JavaScript
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));
OutputMinimum 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.
JavaScript
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);
OutputMinimum 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.
Approach 5: Cycle Detection in Graph
In this approach, the minimum number of swaps required to sort an array is calculated using the concept of cycle detection in graphs. This method involves creating a graph where each node represents an element in the array, and there is an edge between nodes if the elements need to be swapped. By detecting cycles in this graph, we can determine the number of swaps needed to sort the array.
Example: In this example, the function minSwapsCycleDetection calculates the minimum number of swaps by detecting cycles in the permutation of the array elements. The function first creates a sorted version of the array and a visited array to keep track of visited elements. It then iterates through each element, detecting cycles and counting the number of swaps required.
JavaScript
function minSwapsCycleDetection(arr) {
const n = arr.length;
const arrPos = arr.map((value, index) => [value, index]);
arrPos.sort((a, b) => a[0] - b[0]);
const visited = new Array(n).fill(false);
let swaps = 0;
for (let i = 0; i < n; i++) {
if (visited[i] || arrPos[i][1] === i) continue;
let cycleSize = 0;
let j = i;
while (!visited[j]) {
visited[j] = true;
j = arrPos[j][1];
cycleSize++;
}
if (cycleSize > 1) {
swaps += (cycleSize - 1);
}
}
return swaps;
}
const arr2 = [1,2,4,3];
console.log("Minimum swaps required:", minSwapsCycleDetection(arr2));
OutputMinimum swaps required: 1
Approach 6: Using the Indexed Array
In this approach, we calculate the minimum number of swaps required to sort an array by utilizing an indexed array. This involves creating an array of tuples where each tuple contains the element and its original index. We then sort this array of tuples based on the element values. By iterating through the sorted array and swapping elements to their correct positions using the indexed information, we can count the minimum number of swaps needed.
Example : The function minSwapsIndexed calculates the minimum swaps required to sort an array. It works by finding cycles in the index mapping and summing up cycle sizes minus one.
JavaScript
function minSwapsIndexed(arr) {
let indexedArr = arr.map((value, index) => [value, index]);
indexedArr.sort((a, b) => a[0] - b[0]);
let visited = new Array(arr.length).fill(false);
let swapCount = 0;
for (let i = 0; i < indexedArr.length; i++) {
if (visited[i] || indexedArr[i][1] === i) {
continue;
}
let cycleSize = 0;
let j = i;
while (!visited[j]) {
visited[j] = true;
j = indexedArr[j][1];
cycleSize++;
}
if (cycleSize > 0) {
swapCount += (cycleSize - 1);
}
}
return swapCount;
}
let arr1 = [4, 3, 2, 1];
console.log(minSwapsIndexed(arr1));
let arr2 = [1, 5, 4, 3, 2];
console.log(minSwapsIndexed(arr2));
Similar Reads
JavaScript Program for Insertion Sort
What is Insertion Sort Algorithm?Insertion sorting is one of the sorting techniques that is based on iterating the array and finding the right position for every element. It compares the current element to the predecessors, if the element is small compare it with the elements before. Move ahead to a
4 min read
JavaScript Program to Rearrange Array such that Even Positioned are Greater than Odd
In this article, we will cover rearranging arrays such that even positions are greater than odd in JavaScript. Give there is an array that we need to rearrange in the pattern where the even positioned are greater than the odd positioned in JavaScript. We will see the code for each approach along wit
4 min read
JavaScript Program to Find Lexicographically Next Permutation
Given an array of distinct integers, we want to find the lexicographically next permutation of those elements. In simple words, when all the possible permutations of an array are placed in a sorted order, it is the lexicographic order of those permutations. In this case, we have to find the next gre
5 min read
JavaScript Program for Selection Sort
What is Selection Sort in JavaScript?Selection sort is a simple and efficient algorithm that works on selecting either the smallest or the largest element of the list or array and moving it to the correct position. Working of Selection SortConsider the following arrayarr = [ 64, 25, 12, 22, 11]This
3 min read
JavaScript Program for Quick Sort
What is Quick Sort Algorithm?Quick sort is one of the sorting algorithms that works on the idea of divide and conquer. It takes an element as a pivot and partitions the given array around that pivot by placing it in the correct position in the sorted array. The pivot element can be selected in the f
4 min read
Javascript Program to Sort an array in wave form
Given an unsorted array of integers, sort the array into a wave like array. An array 'arr[0..n-1]' is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= .....Examples: Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80} Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} OR {
4 min read
JavaScript Progam to rearrange an array in maximum minimum form using Two Pointer Technique
In this article, we are going to learn about rearranging an array in maximum minimum form using the Pointer Technique in JavaScript. Rearranging an array in maximum-minimum form with the Two Pointer Technique involves sorting the array, then alternately selecting elements from the smallest and large
4 min read
Javascript Program For Rearranging An Array In Maximum Minimum Form - Set 2 (O(1) extra space)
Given a sorted array of positive integers, rearrange the array alternately i.e first element should be the maximum value, second minimum value, third-second max, fourth-second min and so on. Examples:Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2, 5, 3, 4}Input: arr[] = {1, 2, 3, 4
5 min read
Javascript Program to Rearrange positive and negative numbers in O(n) time and O(1) extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If the
3 min read
Javascript Program to Check if it is possible to sort the array after rotating it
Given an array of size N, the task is to determine whether its possible to sort the array or not by just one shuffle. In one shuffle, we can shift some contiguous elements from the end of the array and place it in the front of the array.For eg: A = {2, 3, 1, 2}, we can shift {1, 2} from the end of t
3 min read