Created
February 21, 2018 00:44
-
-
Save ernestlv/8d60bb40521197b84e95e5c575af4917 to your computer and use it in GitHub Desktop.
check if you need just one swap to sort a list of number
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 isOneSwapSort(A){ | |
for ( let f = A.length - 1; f > 0; f--) { | |
for (let i=0; i<f; i++) { | |
if ( A[f] < A[i] ){ | |
let temp = A[i]; | |
A[i] = A[f]; | |
A[f] = temp; | |
if ( isOneSwapSort(A) > 0 ) return 2; //more than one swap | |
return 1; //one swap | |
} | |
} | |
} | |
return 0 //already sorted | |
} | |
function solution(A) { | |
var res = isOneSwapSort(A); | |
return res === 0 || res === 1 ? true : false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment