Advertisement
unknown_0711

Untitled

Nov 27th, 2022
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. public class Main {
  2. public static void main(String[] args) throws java.lang.Exception {
  3. Scanner sc = new Scanner(System.in);
  4. int n = sc.nextInt();
  5. int arr[] = new int[n];
  6. for (int i = 0; i < n; i++)
  7. arr[i] = sc.nextInt();
  8. System.out.println(minSwap(arr, n));
  9. }
  10.  
  11. public static int minSwap(int arr[], int n) {
  12. int ans = 0;
  13. int temp[] = Arrays.copyOfRange(arr, 0, n);
  14. // 2 3 4 1 5
  15. // 1 3 4 2 5
  16. // 1 2 4 3 5
  17.  
  18. // 1 2 3 4 5
  19. HashMap<Integer, Integer> hm = new HashMap<>();
  20. Arrays.sort(temp);
  21. for (int i = 0; i < n; i++) {
  22. hm.put(arr[i], i); // where is arr[i] in array
  23. }
  24. for (int i = 0; i < n; i++) {
  25. if (arr[i] != temp[i]) {
  26. ans++;
  27. swap(arr, i, hm.get(temp[i]), hm);
  28. }
  29. }
  30. return ans;
  31. }
  32.  
  33. public static void swap(int arr[], int curIndex, int sortedIndex, HashMap<Integer, Integer> hm ) {
  34. int tmp = arr[curIndex];
  35. arr[curIndex] = arr[sortedIndex];
  36. arr[sortedIndex] = tmp;
  37.  
  38. hm.put(arr[sortedIndex], sortedIndex);
  39. hm.put(arr[curIndex], curIndex);
  40.  
  41. }
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement