forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinimumSwapsForNIntegers.java
78 lines (64 loc) · 1.71 KB
/
MinimumSwapsForNIntegers.java
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.*;
class MinimumSwapsForNIntegers {
private static int minSwaps(int[] arr) {
int countSwaps = 0;
for(int i=0; i<arr.length; i++) {
//swapping elements if not in their right positions
if (arr[i] != i+1) {
while (arr[i] != i+1) {
int temp = arr[arr[i]-1];
arr[arr[i]-1] = arr[i];
arr[i] = temp;
countSwaps++;
}
}
}
return countSwaps;
}
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
// taking input array
System.out.println("Enter size of array:");
int size = sc.nextInt();
int arr[] = new int[size];
System.out.println("Enter array elements:");
for (int i=0; i<size; i++) {
arr[i] = sc.nextInt();
}
sc.close();
// initial array
System.out.println("Array before sorting:");
for (int i=0; i<size; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
int minSteps = minSwaps(arr);
// final array
System.out.println("Array after sorting:");
for (int i=0; i<size; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("Minimum number of swaps required to sort:" + minSteps);
}
}
/*
Sample input/output:
Enter size of array:
7
Enter array elements:
2
3
7
4
6
1
5
Array before sorting:
2 3 7 4 6 1 5
Array after sorting:
1 2 3 4 5 6 7
Minimum number of swaps required to sort:5
Time Complexity: O(N) where N is the size of array.
Auxiliary Space: O(1)
*/