Skip to content

Instantly share code, notes, and snippets.

@iamwebwiz
Created August 28, 2019 09:08
Show Gist options
  • Save iamwebwiz/bba588b798c408d94a5cdaf3a84ec372 to your computer and use it in GitHub Desktop.
Save iamwebwiz/bba588b798c408d94a5cdaf3a84ec372 to your computer and use it in GitHub Desktop.
A function that find the minimum number of swaps required to sort an unordered array of unique integers into ascending order
/**
* Function to get the minumum swaps required to
* sort an unordered array of unique integers in
* ascending order
*
* @param Array arr
* @returns Number
*/
const minimumSwaps = arr => {
let swaps = 0;
for (let i = 0; i < Math.max(...arr); i++) {
while (arr[i] < i + 1) {
// create temporary store for the value
let temp = arr[i];
// swap values
arr[i] = arr[arr[i] - 1];
arr[temp - 1] = temp;
// increment the counter
swaps++;
}
}
// return number of swaps
return swaps;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment