-
Notifications
You must be signed in to change notification settings - Fork 68
/
Minimum Swaps to Sort #39
50 lines (36 loc) · 1.04 KB
/
Minimum Swaps to Sort #39
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/* Write code to find the minimum number of swaps required to sort the given array in increasing order.
Example:
Input:
A[]= {12, 20, 8, 2, 6 }
Output:
2
Explanation: swap 12 with 2 , swap 20 with 6
*/
public class MinimumSwaps {
public static int findMinimumSwaps(int[] arr) {
int n = arr.length;
int[] temp = Arrays.copyOfRange(arr, 0, n);
Arrays.sort(temp);
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(arr[i], i);
}
int swaps = 0;
for (int i = 0; i < n; i++) {
int num = temp[i];
if (arr[i] != num) {
swaps++;
int tempIndex = map.get(num);
map.put(arr[i], tempIndex);
arr[tempIndex] = arr[i];
arr[i] = num;
}
}
return swaps;
}
public static void main(String[] args) {
int[] arr = {12, 20, 8, 2, 6};
int swaps = findMinimumSwaps(arr);
System.out.println(swaps);
}
}