Skip to content

Instantly share code, notes, and snippets.

@kkabdol
Created January 28, 2019 08:19
Show Gist options
  • Save kkabdol/84d477bd4840f605354e40e3cd064613 to your computer and use it in GitHub Desktop.
Save kkabdol/84d477bd4840f605354e40e3cd064613 to your computer and use it in GitHub Desktop.
Minimum number of swaps required to sort an array
// 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