fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. static int minimumSwaps(int[] arr) {
  11. int swaps = 0;
  12. HashMap<Integer, Integer> hm = new HashMap<>();
  13. for(int i=0; i<arr.length; i++)
  14. hm.put(arr[i],i); //unsorted
  15.  
  16. int [] temp = arr;
  17. Arrays.sort(temp);
  18.  
  19. for(int num: hm.keySet()) {
  20. int index = hm.get(num);
  21. System.out.println(index + " " + num);
  22. if(temp[index] != arr[index]) {
  23. int actual_index = hm.get(temp[index]);
  24. int t = arr[index];
  25. arr[index] = arr[actual_index];
  26. arr[actual_index] = t;
  27. swaps++;
  28. }
  29. }
  30. return swaps;
  31. }
  32.  
  33.  
  34. public static void main (String[] args) throws java.lang.Exception
  35. {
  36. // your code goes here
  37. int arr[] = {1, 3, 5, 2, 4, 6, 7};
  38. System.out.println(minimumSwaps(arr));
  39. }
  40. }
Success #stdin #stdout 0.17s 35960KB
stdin
Standard input is empty
stdout
0 1
3 2
1 3
4 4
2 5
5 6
6 7
0