Here are some tips for finding solutions to java problems about “minimum swaps to sort an array” Code Answer. We are going to list out some java programming problem, you can find the solution for your programming question if you get stuck in coding. Getting stuck in programming is quite normal for all the developers. Most of the beginners and even experienced programmers take help from some resources but that doesn’t mean they are dumb or bad programmers. Below are some solution about “minimum swaps to sort an array” Code Answer.
minimum swaps to sort an array
xxxxxxxxxx
1
import java.io.*;
2
import java.math.*;
3
import java.util.*;
4
5
public class Swap {
6
static int minimumSwaps(int[] arr) {
7
int swap=0;
8
boolean visited[]=new boolean[arr.length];
9
10
for(int i=0;i<arr.length;i++){
11
int j=i,cycle=0;
12
13
while(!visited[j]){
14
visited[j]=true;
15
j=arr[j]-1;
16
cycle++;
17
}
18
19
if(cycle!=0)
20
swap+=cycle-1;
21
}
22
return swap;
23
}
24
25
public static void main(String[] args) {
26
27
Scanner scanner = new Scanner(System.in);
28
int n = scanner.nextInt();
29
int[] arr = new int[n];
30
31
for (int i = 0; i < n; i++) {
32
arr[i] = scanner.nextInt();
33
}
34
35
int res = minimumSwaps(arr);
36
System.out.println(res);
37
scanner.close();
38
}
39
}
40