Skip to content

Instantly share code, notes, and snippets.

@akinyeleolat
Last active September 3, 2019 16:10
Show Gist options
  • Save akinyeleolat/41f9975c68e309d8b3304e5966be7bc0 to your computer and use it in GitHub Desktop.
Save akinyeleolat/41f9975c68e309d8b3304e5966be7bc0 to your computer and use it in GitHub Desktop.
Minimum swap
let array = [3,1,2]
let newArr = []
const minimumSwaps = (array) => {
let count=0;
const expectedArr = array.slice().sort((a,b)=>{
return a-b
})
console.log(expectedArr)
let loc;
let arrLength = array.length;
while(arrLength--){
if(array[arrLength] === expectedArr[arrLength]) continue;
loc = array.indexOf(expectedArr[arrLength]);
//swap
[array[arrLength],array[loc]] = [array[loc],array[arrLength]];
count++;
}
console.log(count)
return count;
}
minimumSwaps(array)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment