Find the minimum number of swaps to sort unsorted array.

i   arr                         swap (indices)
0 [7, 1, 3, 2, 4, 5, 6] swap (0,3)
1 [2, 1, 3, 7, 4, 5, 6] swap (0,1)
2 [1, 2, 3, 7, 4, 5, 6] swap (3,4)
3 [1, 2, 3, 4, 7, 5, 6] swap (4,5)
4 [1, 2, 3, 4, 5, 7, 6] swap (5,6)
5 [1, 2, 3, 4, 5, 6, 7]
  • int arr[n]: an unordered array of integers
  • int: the minimum number of swaps to sort the array
4
4 3 1 2
3
5
2 3 4 1 5
3
static int minimumSwaps(int[] arr) {int swap = 0 ;for(int i = 0 ;i < arr.Length ;i++)
{
while(arr[i]!=i+1)
{
if(arr[i] != i+1)
{
int swapIndex = arr[i]-1;
int temp = arr[swapIndex];
arr[swapIndex] = arr[i];
arr[i] = temp;
swap++;
}
}
}
return swap;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store