Skip to content

Instantly share code, notes, and snippets.

@psaitu
Created August 5, 2019 16:24
Show Gist options
  • Save psaitu/a71d8dcb805d85bc78febe2a4b05ca24 to your computer and use it in GitHub Desktop.
Save psaitu/a71d8dcb805d85bc78febe2a4b05ca24 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
// https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/
// https://www.includehelp.com/java-programs/minimum-swaps-required-to-sort-an-array.aspx
public static int minswaps(int[] a) {
int n = a.length;
boolean[] visited = new boolean[n];
int number_of_swaps = 0;
for(int i = 0; i < n; i++) {
int j = i;
int cycles = 0;
while (!visited[j]) {
visited[j] = true;
j = a[j] - 1;
cycles++;
}
if(cycles != 0) { number_of_swaps += cycles - 1; }
}
return number_of_swaps;
}
public static void main(String[] args) {
int[] arr = new int[]{4, 3, 2, 1};
System.out.println(minswaps(arr));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment