Created
August 3, 2016 22:09
-
-
Save andrew310/202999191d9d42720d02a70f58f43963 to your computer and use it in GitHub Desktop.
Can Array Be Sorted with One Swap?
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 solution(A) { | |
| var newArr = A.slice(); //ceates a copy | |
| newArr.sort( function(a, b){return a-b;});//sort the copy | |
| var counter = 0; | |
| for(var i = 0; i < A.length; i++){ //compare to original | |
| if (newArr[i] != A[i]) counter++; | |
| } | |
| return counter > 2 ? false : true; | |
| } | |
| /*this solution just sorts the array and counts how many items are not in their original place. | |
| / two misplaced items = 1 swap. | |
| / IS THIS CORRECT?? Have only tested on a few inputs. | |
| /* | |
| /* Another idea: use selection Sort and count the swaps made... | |
| /* |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment