![]() |
VOOZH | about |
Given an array arr[] of distinct elements, find the minimum number of swaps required to sort the array.
Examples:
Input: arr[] = [2, 8, 5, 4]
Output: 1
Explanation: Swap 8 with 4 to get the sorted array.Input: arr[] = [10, 19, 6, 3, 5]
Output: 2
Explanation: Swap 10 with 3 and 19 with 5 to get the sorted array.Input: arr[] = [1, 3, 4, 5, 6]
Output: 0
Explanation: Input array is already sorted.
Table of Content
The idea is to use a hash map to store each element of the given array along with its index. We also create a temporary array that stores all the elements of the input array in sorted order. As we traverse the input array, if the current element arr[i] is not in its correct position, we swap it with the element that should be at i i.e., temp[i]. After this, we increment the swap count and update the indices in the hash map accordingly.
2
This approach uses cycle detection method to find out the minimum number of swaps required to sort the array. If an element is not in its correct position, it indicates that it is a part of a cycle with one or more other elements that also need to be moved. For example, if element A is in the position of element B, and element B is in the position of element C, and so on, until it comes back to A, it forms a cycle. And to sort the elements in the cycle, we need cycleSize - 1 swaps, as each swap places one element in its correct position, and the last element will automatically be in its correct place.
We use a hash map to store the original indices of each element and a visited array to mark elements that have already been included in a cycle. Next, we sort the array. As we traverse it, if an element hasnโt been visited and isnโt in its correct position, we trace the cycle formed by the misplaced elements and find its size. The swap count is then updated by cycleSize - 1.
2
Related Article:
Number of swaps to sort when only adjacent swapping allowed