Last active
September 3, 2019 16:10
-
-
Save akinyeleolat/41f9975c68e309d8b3304e5966be7bc0 to your computer and use it in GitHub Desktop.
Minimum swap
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
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