Created
August 28, 2019 09:08
-
-
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
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
/** | |
* 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