Advertisement
unknown_0711

Untitled

Nov 28th, 2022
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.67 KB | None | 0 0
  1. static int MinimumSwapsToSort(int n, int[] nums){
  2. HashMap<Integer, Integer> map = new HashMap<>();
  3. for(int i=0;i<n;i++)
  4. map.put(nums[i], i);
  5.  
  6. Arrays.sort(nums);
  7. boolean[] visited = new boolean[n];
  8. Arrays.fill(visited, false);
  9. int ans = 0;
  10. for(int i=0;i<n;i++) {
  11. if(visited[i] || map.get(nums[i]) == i)
  12. continue;
  13.  
  14. int j = i, cycle_size = 0;
  15. while(!visited[j]) {
  16. visited[j] = true;
  17. j = map.get(nums[j]);
  18. cycle_size++;
  19. }
  20. if(cycle_size > 0) {
  21. ans += (cycle_size - 1);
  22. }
  23. }
  24. return ans;
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement