Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Main {
- public static void main(String[] args) throws java.lang.Exception {
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- int arr[] = new int[n];
- for (int i = 0; i < n; i++)
- arr[i] = sc.nextInt();
- System.out.println(minSwap(arr, n));
- }
- public static int minSwap(int arr[], int n) {
- int ans = 0;
- int temp[] = Arrays.copyOfRange(arr, 0, n);
- // 2 3 4 1 5
- // 1 3 4 2 5
- // 1 2 4 3 5
- // 1 2 3 4 5
- HashMap<Integer, Integer> hm = new HashMap<>();
- Arrays.sort(temp);
- for (int i = 0; i < n; i++) {
- hm.put(arr[i], i); // where is arr[i] in array
- }
- for (int i = 0; i < n; i++) {
- if (arr[i] != temp[i]) {
- ans++;
- swap(arr, i, hm.get(temp[i]), hm);
- }
- }
- return ans;
- }
- public static void swap(int arr[], int curIndex, int sortedIndex, HashMap<Integer, Integer> hm ) {
- int tmp = arr[curIndex];
- arr[curIndex] = arr[sortedIndex];
- arr[sortedIndex] = tmp;
- hm.put(arr[sortedIndex], sortedIndex);
- hm.put(arr[curIndex], curIndex);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement