Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // test arrays
- var x = [1, 2, 3];
- var y = [1, 3, 2];
- var z = [3, 2, 1];
- // global swap counter
- var swaps = 0;
- // custom sort function that counts swaps
- function swapcount(a, b){
- if (a < b) {
- return -1;
- } else if (a > b) {
- swaps++;
- return 1;
- }
- return 0;
- }
- // shallow compare two arrays
- function compareAr(a, b) {
- if (a.length !== b.length) return false;
- for (var i = 0; i < a.length; i++) {
- if (a[i] !== b[i]) return false;
- }
- return true;
- }
- // test function
- function solution(a) {
- var sorted = a.slice().sort();
- // true when already sorted
- if (compareAr(a, sorted)) return true;
- // count swaps
- swaps = 0
- a.sort(swapcount);
- // false when more than one swap is needed
- if (swaps > 1) {
- return false;
- }
- // true when sorated with one swap
- return true;
- }
- [x, y, z].forEach(ar => console.log(solution(ar)));
Add Comment
Please, Sign In to add comment