Skip to content

Instantly share code, notes, and snippets.

@andrew310
Created August 3, 2016 22:09
Show Gist options
  • Select an option

  • Save andrew310/202999191d9d42720d02a70f58f43963 to your computer and use it in GitHub Desktop.

Select an option

Save andrew310/202999191d9d42720d02a70f58f43963 to your computer and use it in GitHub Desktop.
Can Array Be Sorted with One Swap?
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