-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsortarray.java
More file actions
49 lines (38 loc) · 835 Bytes
/
Copy pathsortarray.java
File metadata and controls
49 lines (38 loc) · 835 Bytes
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
import java.util.*;
public class sortarray {
public static int minswaps(int[] arr, int n)
{
int res = 0;
int[] temp = Arrays.copyOfRange(arr, 0, n);
Arrays.sort(temp);
for (int i = 0; i < n; i++)
{
if (arr[i] != temp[i])
{
res++;
swap(arr, i, index(arr, temp[i]));
}
}
return res;
}
public static void swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static int index(int[] arr, int a)
{
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == a) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {2,3,1,4,5};
System.out.println("Minimum swaps required: "+minswaps(arr, arr.length));
}
}