Created
April 17, 2018 09:11
-
-
Save amulyakashyap09/a5cdbb825445eef202099b3a1d9c57d6 to your computer and use it in GitHub Desktop.
find minimum number of swaps to reorder the array in ascending
This file contains hidden or 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 minSwaps(arr) { | |
//using selection sort O(N^2) | |
let n = arr.length; | |
let initial_min_no = 0, | |
initial_min_index = 0, | |
swaps = 0; | |
for (let i = 0; i < n - 1; i++) { | |
initial_min_no = arr[i]; | |
initial_min_index = i; | |
for (let j = i + 1; j < n; j++) { | |
if (initial_min_no > arr[j]) { | |
initial_min_no = arr[j]; | |
initial_min_index = j; | |
} | |
} | |
if (initial_min_index !== i) { | |
let temp = arr[i]; | |
arr[i] = arr[initial_min_index]; | |
arr[initial_min_index] = temp; | |
swaps++; | |
} | |
} | |
return swaps; | |
} | |
let swaps = minSwaps([1,6,2,5,3,4]); | |
console.log("minimum number of swaps : ", swaps); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment