Created
January 28, 2019 08:19
-
-
Save kkabdol/84d477bd4840f605354e40e3cd064613 to your computer and use it in GitHub Desktop.
Minimum number of swaps required 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
// https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/ | |
int minimumSwaps( vector<int> arr ) { | |
pair< int, int > arrPos[ arr.size() ]; | |
for( size_t i = 0; i < arr.size(); ++i ) | |
{ | |
arrPos[ i ].first = arr[ i ]; | |
arrPos[ i ].second = i; | |
} | |
sort( arrPos, arrPos + arr.size() ); | |
vector<bool> vis( arr.size(), false ); | |
int swaps = 0; | |
for( size_t i = 0; i < arr.size(); ++i ) | |
{ | |
if( vis[ i ] || arrPos[ i ].second == i ) | |
{ | |
continue; | |
} | |
int cycle_size = 0; | |
size_t j = i; | |
while( !vis[ j ] ) | |
{ | |
vis[ j ] = true; | |
j = arrPos[ j ].second; | |
cycle_size++; | |
} | |
if( cycle_size > 0 ) | |
{ | |
swaps += cycle_size - 1; | |
} | |
} | |
return swaps; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment