Given an array of n distinct elements, find the minimum number of swaps required to sort the array.
Examples:
Input : {4, 3, 2, 1}
Output : 2
Explanation : Swap index 0 with 3 and 1 with 2 to
form the sorted array {1, 2, 3, 4}.
Input : {1, 5, 4, 3, 2}
Output : 2
This can be easily done by visualizing the problem as a graph. We will have n nodes and an edge directed from node i to node j if the element at i’th index must be present at j’th index in the sorted array.
Graph for {4, 3, 2, 1}
The graph will now contain many non-intersecting cycles. Now a cycle with 2 nodes will only require 1 swap to reach the correct ordering, similarly a cycle with 3 nodes will only require 2 swap to do so.
classSolution {staticclassPair {int v, i;Pair(int v,int i) {this.v= v;this.i= i; } }publicintminSwaps(int[] arr,int N) {Pair[] copy =newPair[N];for (int i =0; i < N; i++) copy[i] =newPair(arr[i], i);Arrays.sort(copy, (a, b) ->a.v-b.v);int count =0;boolean[] visited =newboolean[N];// number of swaps = cycle length - 1for (int i =0; i < N; i++) {// If element is at correct positionif (copy[i].i== i || visited[i])continue;else {// Cycleint size =0;int index = i;while (!visited[index]) { visited[index] =true; index = copy[index].i; size++; } count += size -1; } }return count; }}