-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinimumNumberOfSwapsToSort.java
368 lines (313 loc) · 11.5 KB
/
MinimumNumberOfSwapsToSort.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package Algorithms.GreedyAlgorithms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Srinivas Vadige, [email protected]
* @since 23 Nov 2024
*/
public class MinimumNumberOfSwapsToSort {
public static void main(String[] args) {
int[] arr = new int[]{2, 3, 88, 3, 4, 8, 5}, nonContiguousArr = new int[]{6, 3, 1, 2, 4, 5};
int[] temp = nonContiguousArr.clone();
System.out.println("Contiguous numbers minSwaps of " + Arrays.toString(temp));
System.out.println("minSwaps using brute force: " + minSwapsBruteForce(temp));
temp = nonContiguousArr.clone();
System.out.println("minSwaps using HashMap: " + minSwapsUsingHashMap(temp));
temp = nonContiguousArr.clone();
System.out.println("minSwaps using List<Map.Entry>: " + minSwapsUsingMapEntryList(temp));
temp = arr.clone();
System.out.println("\nNon-contiguous numbers minSwaps of " + Arrays.toString(temp) );
System.out.println("minSwaps4: " + minSwaps4(temp));
temp = arr.clone();
System.out.println("minSwaps5: " + minSwaps5(temp));
temp = arr.clone();
System.out.println("minSwaps6: " + minSwaps6(temp));
temp = arr.clone();
System.out.println("minSwaps7: " + minSwaps7(temp));
}
/**
* Contiguous Numbers ------------------------------------------------------------------------------
*
* Must start from 1
* No duplicates
*
*/
//
public static int minSwapsBruteForce(int[] arr) {
int minSwaps = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != i + 1) {
for (int j = i; j < arr.length; j++) {
if (arr[j] == i + 1) {
swap(arr, i, j);
minSwaps++;
break;
}
}
}
}
return minSwaps;
}
public static int minSwapsUsingHashMap(int[] arr) {
int swaps = 0;
HashMap<Integer, Integer> map = new HashMap<>(); // {expected num, curr num} ==> num=curr
boolean[] visited = new boolean[arr.length + 1];
for (int i = 1; i <= arr.length; i++)
map.put(i, arr[i-1]); // [1, 4, 3, 2] --> {1=1, 2=4, 3=3, 4=2}, we know that hashMap sorts the keys by default
for (int num = 1; num <= arr.length; num++) { // expected num
if (!visited[num]) {
visited[num] = true;
int curr = map.get(num);
if (num == curr) // is num at correct position?
continue;
else {
// [1, 4, 3, 2]
// {1=1, 2=4, 3=3, 4=2} ---> exp num = curr
// num=2, curr=4, next=2
while (!visited[curr]) {
visited[curr] = true;
int next = map.get(curr); // if curr != expected num, then check what's in that curr's position current number, i.e while loop until we visited all next nums
curr = next;
swaps++;
}
}
}
}
return swaps;
}
public static int minSwapsUsingMapEntryList(int[] arr) {
int swaps = 0;
List<Map.Entry<Integer, Integer>> lst = new ArrayList<>(); // List<{num, index}>
//---> so we have 3 properties here - list index or sorted index, expected num and given index
for (int i = 0; i < arr.length; i++)
lst.add(Map.entry(arr[i], i)); // by default the keys i.e nums are sorted
lst.sort(Comparator.comparing(Map.Entry::getKey)); // or lst.sort((o1, o2) -> o1.getKey() - o2.getKey()); sort by needed nums
/*
0, 1, 2, 3, 4, 5 ----> indices
[6, 3, 1, 2, 4, 5] ----> nums
0 1 2 3 4 5 ----> indices of lst
[1=2, 2=3, 3=1, 4=4, 5=5, 6=0] ----> lst swap 0
[3=1*, 2=3, 1=2*, 4=4, 5=5, 6=0] ----> lst swap 1
[2=3*, 3=1*, 1=2, 4=4, 5=5, 6=0] ----> lst swap 2
[4=4*, 3=1, 1=2, 2=3*, 5=5, 6=0] ----> lst swap 3
[5=5*, 3=1, 1=2, 2=3, 4=4*, 6=0] ----> lst swap 4
[6=0*, 3=1, 1=2, 2=3, 4=4, 5=5*] ----> lst swap 5
*/
// check how many swaps needed to convert the lst to before sort
for (int i = 0; i < lst.size(); i++) {
Map.Entry<Integer, Integer> entry = lst.get(i);
if (entry.getValue() != i ) { // lst sorted - given index != lst index
System.out.println(lst);
// swap(arr[], i, j)
int givenIndex = entry.getValue();
lst.set(i, lst.get(givenIndex));
lst.set(givenIndex, entry);
swaps++;
i--; // maintain same lst index until we obtain the exact swap i.e (lst num == arr num) i.e back to original form before sorting the lst
}
}
System.out.println(lst);
return swaps;
}
public static int minSwapsForContiguousOrder2(int[] arr) {
int minimumSwaps = 0;
for (int i = 0; i < arr.length; i++) {
int current = arr[i];
while(current != i + 1){
int temp = arr[current - 1];
arr[current - 1] = current;
arr[i] = temp;
minimumSwaps++;
current = temp;
}
}
return minimumSwaps;
}
public static int minSwapsForContiguousOrder3(int[] arr) {
int i = 0;
int swap = 0;
while( i < arr.length ) {
if (arr[i] == i+1)
i += 1;
else{
int index = arr[i] -1;
swap(arr, i, index);
swap += 1;
}
}
return swap;
}
public static int minSwapsForContiguousOrder4(int[] arr) {
boolean isSorted = false;
int curr = 0; // current pointer index
int swaps = 0;
while (!isSorted) {
if (curr == arr.length) {
isSorted = true;
break;
}
if (curr+1 == arr[curr])
curr += 1;
else {
int ind = arr[curr] - 1;
swap(arr, curr, ind);
swaps += 1;
}
}
return swaps;
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private static class Pair { // like 'cpp STL <utility> header - pair container' or Map.entry() or AbstractMap.SimpleEntry
int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
}
private static int indexOf(int[] arr, int ele) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == ele) {
return i;
}
}
return -1;
}
/**
* Non-Contiguous numbers ------------------------------------------------------------------------------
*
* No duplicates
* No contiguity
*/
/**
* @TimeComplexity O(nlogn)
*/
public static int minSwaps4(int[] arr) {
int n = arr.length;
// Create two arrays and use as pairs where first array is element and second array is position of first element
ArrayList<Pair> arrPos = new ArrayList<Pair>();
for (int i = 0; i < n; i++)
arrPos.add(new Pair(arr[i], i));
arrPos.sort( new Comparator<Pair>() { // or arrPos.sort((o1, o2) -> o1.first - o2.first);
@Override
public int compare( Pair o1, Pair o2) {
if (o1.first < o2.first)
return -1;
else if (o1.first == o2.first)
return 0;
else
return 1;
}
});
// To keep track of visited elements. Initialize all elements as not visited or false.
Boolean[] vis = new Boolean[n];
Arrays.fill(vis, false);
// Initialize result
int ans = 0;
// Traverse array elements
for (int i = 0; i < n; i++) {
// already swapped and corrected or already present at correct pos
if (vis[i] || arrPos.get(i).second == i)
continue;
// find out the number of node in this cycle and add in ans
int cycle_size = 0;
int j = i;
while (!vis[j]) {
vis[j] = true;
// move to next node
j = arrPos.get(j).second;
cycle_size++;
}
// Update answer by adding current cycle.
if (cycle_size > 0) {
ans += (cycle_size - 1);
}
}
// Return result
return ans;
}
/**
* @TimeComplexity O(nlogn)
*/
public static int minSwaps5(int[] nums) {
int len = nums.length;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < len; i++)
map.put(nums[i], i);
Arrays.sort(nums);
// To keep track of visited elements. Initialize all elements as not visited or false.
boolean[] visited = new boolean[len];
Arrays.fill(visited, false);
// Initialize result
int ans = 0;
for (int i = 0; i < len; i++) {
// already swapped and corrected or already present at correct pos
if (visited[i] || map.get(nums[i]) == i)
continue;
int j = i, cycle_size = 0;
while (!visited[j]) {
visited[j] = true;
// move to next node
j = map.get(nums[j]);
cycle_size++;
}
// Update answer by adding current cycle.
if (cycle_size > 0) {
ans += (cycle_size - 1);
}
}
return ans;
}
/**
* @TimeComplexity: O(N^2)
*/
public static int minSwaps6(int[] arr) {
int ans = 0;
int N = arr.length;
int[] temp = Arrays.copyOfRange(arr, 0, N);
Arrays.sort(temp);
for (int i = 0; i < N; i++) {
// This is checking whether the current element is at the right place or not
if (arr[i] != temp[i]) {
ans++;
// Swap the current element with the right index so that arr[0] to arr[i] is sorted
swap(arr, i, indexOf(arr, temp[i]));
}
}
return ans;
}
/**
* @TimeComplexity O(nlogn)
*/
public static int minSwaps7(int[] arr) {
int ans = 0;
int N = arr.length;
int[] temp = Arrays.copyOfRange(arr, 0, N);
// Hashmap which stores the indexes of the input array
HashMap<Integer, Integer> h = new HashMap<Integer, Integer>();
Arrays.sort(temp);
for (int i = 0; i < N; i++) {
h.put(arr[i], i);
}
for (int i = 0; i < N; i++) {
// This is checking whether the current element is at the right place or not
if (arr[i] != temp[i]) {
ans++;
int init = arr[i];
// If not, swap this element with the index of the element which should come here
swap(arr, i, h.get(temp[i]));
// Update the indexes in the hashmap accordingly
h.put(init, h.get(temp[i]));
h.put(temp[i], i);
}
}
return ans;
}
}