Skip to content

Instantly share code, notes, and snippets.

@randyhbh
Created December 18, 2018 23:35
Show Gist options
  • Save randyhbh/10116825de57ec18a8e3341d9e5b5444 to your computer and use it in GitHub Desktop.
Save randyhbh/10116825de57ec18a8e3341d9e5b5444 to your computer and use it in GitHub Desktop.
Return an integer representing the minimum number of swaps to sort the array.
public class Main {
public static void main(String[] args) {
int [] a = new int[]{4,3,1,2};
minimumSwaps(a);
}
static int minimumSwaps(int[] arr) {
int swapsCount = 0;
int arraySize = arr.length;
int[] sortedArray = arr.clone();
Arrays.sort(sortedArray);
for(int i = 0; i < arraySize; i++) {
if (sortedArray[i] != arr[i])
swapsCount++;
for(int j = i+1; j < arraySize; j++) {
if (arr[j] == sortedArray[i]) {
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
break;
}
}
}
return swapsCount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment