1+ /*
2+ Here, We can compare a sorted array to the original
3+ and just keep track of the differences. As we
4+ go we will need to perform the swaps, becasue we
5+ re not guranteed 1 swap will fix both elements.
6+ We will do this on both a ascending sort and a
7+ descending sort as both meet the minimal
8+ requirement
9+
10+ Time Complexity: O(n log(n)) //We must sort the input
11+ Space Complexity: O(n) //We store the input in an array
12+ */
13+
14+ import java .io .*;
15+ import java .util .*;
16+
17+ public class solution {
18+
19+ public static void main (String [] args ) {
20+ Scanner input = new Scanner (System .in );
21+ int n = input .nextInt ();
22+
23+ int sortedSwaps = 0 ;
24+ int [] homework = new int [n ];
25+ Integer [] homeworkSorted = new Integer [n ];
26+ Map <Integer ,Integer > original = new HashMap <>();
27+
28+ int sortedReverseSwaps = 0 ;
29+ int [] homework2ndCopy = new int [n ];
30+ Map <Integer ,Integer > original2ndCopy = new HashMap <>();
31+
32+ //Initialize our arrays and maps
33+ for (int i = 0 ; i < n ; i ++)
34+ {
35+ homeworkSorted [i ] = input .nextInt ();
36+ homework [i ] = homeworkSorted [i ];
37+ homework2ndCopy [i ] = homeworkSorted [i ];
38+ original .put (homework [i ],i );
39+ original2ndCopy .put (homework2ndCopy [i ],i );
40+ }
41+
42+ Arrays .sort (homeworkSorted );//Sort the input ascending
43+
44+ for (int i = 0 ; i < n ; i ++)
45+ {
46+ if (homework [i ] != homeworkSorted [i ])
47+ {
48+ //swap the element from homework to the right position
49+ int tmp = homework [i ];
50+ homework [i ] = homework [original .get (homeworkSorted [i ])];
51+ homework [original .get (homeworkSorted [i ])] = tmp ;
52+ //Update index after swap
53+ original .put (tmp ,original .get (homeworkSorted [i ]));
54+ sortedSwaps ++;
55+ }
56+ }
57+
58+ Arrays .sort (homeworkSorted , Collections .reverseOrder ());//Sort the input descending
59+
60+ for (int i = 0 ; i < n ; i ++)
61+ {
62+ if (homework2ndCopy [i ] != homeworkSorted [i ])
63+ {
64+ //swap the element from homework to the right position
65+ int tmp = homework2ndCopy [i ];
66+ homework2ndCopy [i ] = homework2ndCopy [original .get (homeworkSorted [i ])];
67+ homework2ndCopy [original2ndCopy .get (homeworkSorted [i ])] = tmp ;
68+ //Update index after swap
69+ original2ndCopy .put (tmp , original2ndCopy .get (homeworkSorted [i ]));
70+ sortedReverseSwaps ++;
71+ }
72+ }
73+ System .out .println (Math .min (sortedSwaps ,sortedReverseSwaps ));//Choose the smallest of the two possible smallest
74+ }
75+ }
0 commit comments