Created
December 7, 2020 05:50
-
-
Save anish000kumar/48a8811c929985e387e2884ecbecd72b to your computer and use it in GitHub Desktop.
Minimum swaps to sort an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def minSwaps(arr, N): | |
newArr = [ (arr[i], i) for i in range(len(arr)) ] | |
newArr.sort() | |
ans = 0 | |
for i in range(len(newArr)): | |
j = newArr[i][1] | |
while newArr[i][1] != newArr[j][1]: | |
newArr[i], newArr[j] = newArr[j], newArr[i] | |
ans += 1 | |
j = newArr[i][1] | |
return ans |
Author
anish000kumar
commented
Dec 7, 2020
- swaps required to go from initial -> sorted version is same as swaps required from sorted -> initial version
- sort the array , while keeping track of indices
- Now indices are unsorted, but can be sorted using cyclic sort
- sort indices using cyclic sort to get the minimum no. of swaps
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment