1

I want to check if a list can be sorted by performing at most one swap operation, and I want to return true if it does. Otherwise, I want to return false.

For example, the input

A = [1,2,3,4,5]

should result in true because it is already sorted.

A = [1,2,5,4,3]

should result in true because with one swap, involving 5 and 3, the list is sorted.

A = [1,2,5,3,4]

should result in false because it requires more than one swap to sort.

My code is below. It returns true if A is already sorted, but it returns undefined if it is not sorted but can be sorted with one swap.

Can someone help me find the problem?

    function solution(A) {
        var count=0;
        for(var k=0; k<A.length; k++) //check if sorted
        {
            if(A[k] <= A[k+1])
                count++;
            else
                break;
        }
        if (count === A.length - 1) //if already sorted return true
        {
            return true;
        }


        for(var i=0; i<A.length; i++)   //if not sorted lets check
        {
            var temp=0;
            for(var j=i+1; j<A.length; j++)
            {
               if(A[i] > A[j]) //swap only if A[i] > A[j]
               {
                    temp = A[i];
                    A[i] = A[j];
                    A[j] = temp;
//check if sorted
               }
            }
        }
    }

I want to check if the array is sorted after every swap. How can I do that ?

Mozein
  • 787
  • 5
  • 19
  • 33
  • Wouldn't it just be `return (count == A.length - 1 || count == A.length - 3)` ? – 000 May 02 '15 at 06:17

3 Answers3

5

The naive approach that tries every possible swap and checks the result takes O(n3) time with respect to the length of the array. The smarter approach of finding the first out-of-order pair and trying to fix it by swapping in every subsequent element takes O(n2) time. The approach of sorting the array and comparing it to the original takes O(n log n) time. Can we do even better?

Yes, we can solve this problem in linear time. We start by looking for an inverted pair of adjacent elements, meaning that the one on the left is bigger than the one on the right. If there is no such pair, the array is already sorted.

Otherwise, we find the leftmost such pair. Let's take the larger element of this pair, namely the one on the left, and call it x. If x is the last of a sequence of equal elements, let's take the leftmost such element because when we swap x with a smaller element y, we want y to occur before every element equal to x.

Now we scan to the right of the inverted pair for the earliest element that is at least as big as x. Once we find such an element, we take the element immediately before it and call this element y. If there is no such element, let y be the last element of the array.

If the array can be sorted in one swap, it is necessary and sufficient to swap x and y. Consider the cases:

  • If all elements to the right of the inverted pair are smaller than x, it is necessary for x to be moved past all of them. Therefore, we swap x with the last element of the array.

  • Otherwise, consider all elements to the right of x that are bigger than x. In a sorted array, x must occur before all of them, but x must be moved past elements that are smaller than it. Therefore, we find the earliest element to the right of the inverted pair that is at least as big as x, and we swap x into the position immediately before it.

// Returns true if and only if A can be sorted with at most one swap.
function almostSorted(A) {
  for (var i = 1; i < A.length; ++i) {
    // Look for an inverted adjacent pair.
    if (A[i-1] <= A[i]) {
      continue;
    }
    var x = A[i-1],
        left = i-1;
    // If x is one of a sequence of identical elements, take the leftmost.
    while (left-1 >= 0 && A[left-1] == x) {
      --left;
    }
    // Scan past the inverted pair for the earliest element no smaller than x.
    for (++i; i < A.length; ++i) {
      if (A[i] >= x) {
        break;  // If we never break here, i will be equal to A.length.
      }
    }
    // Let y be the element before the earliest element no smaller than x.
    var right = i-1,
        y = A[right];  
    // Swap x and y.
    A[left] = y;
    A[right] = x;
    // Is the array sorted now?
    for (i = (left == 0 ? 1 : left); i < A.length; ++i) {
      if (A[i-1] > A[i]) {
        return false;
      }
    }
    return true;  // One swap was enough to sort the array.
  }
  return true;  // The array is already sorted.
}

// A few tests.
function test(A) {
  document.write('['+A.join(', ')+']');
  var result = almostSorted(A);
  document.write(': <span class="', result, '">', result, '</span>');
  if (result) {
    document.write(' &rarr; ', '['+A.join(', ')+']');
  }
  document.write('<br />');
}
test([1, 2, 5, 4, 3]);
test([1, 2, 3, 5, 4]);
test([1, 4, 3, 2, 5]);
test([1, 5, 4, 3, 2]);
test([1, 5, 3, 3, 7]);
test([2, 2, 1, 3, 7]);
test([2, 3, 1, 3, 7]);
test([1, 3, 1, 3, 7]);
test([2, 1, 1, 3, 7]);
body {
  font-family: sans-serif;
  font-size: 17px;
  color: #333;
}
.false {
  color: #b23c3c;
}
.true {
  color: #5c7b51;
}
Michael Laszlo
  • 12,009
  • 2
  • 29
  • 47
  • This doesn't give you the minimum number of swaps. It gives you the minimum number of swaps only if you're limited to adjacent swaps (which we aren't for this problem). – Asad Saeeduddin May 02 '15 at 06:52
  • +1 for a solution that works, but isn't this also technically O(n^2) worst case because of the nested loop? – Asad Saeeduddin May 02 '15 at 07:34
  • No, because each loop is used at most once. Notice the `return` statement after each loop. – Michael Laszlo May 02 '15 at 07:39
  • very smart anwser. Appreciate showing me the efficient way – Mozein May 02 '15 at 07:48
  • You'll hate me for this, but I have to pester you again. You're getting false for the last item in your test cases, but that should be true, no? Swap the second 3 with the 5 and it works. – Asad Saeeduddin May 02 '15 at 07:57
  • 1
    I have improved the code and the explanation that precedes it. Now the code only uses a single variable `i` to scan the array, and I introduce the variables `left` and `right` for the indices of the elements to be swapped. – Michael Laszlo May 02 '15 at 09:46
1
see following example.
set it into a function. i used it in window onload

var a=[1,2,5,4,3];
var aTmp=a.slice(0);
aTmp.sort();
var cnt=0;
for(var i=0;i<a.length;i++){
   if(a[i]!=aTmp[i]){     
    cnt++;
   }
   if(cnt>2)
     return false;
}
if(cnt==0 || cnt==2)
    return true;
else
    return false;
ros001
  • 23
  • 5
0

If you don't want to sort the array, it's better to count the number of times that arr[i] > arr[j] (j > i) and return if count >= 1.

Use this as a helper method:

function isArraySorted(arr){
      for(var i = 0; i < arr.length ; ++i) {
          if(arr[i] > arr[i+1])
              return false;
       }

       return true;
}

This is your new function:

 function solution(A) {
     if (isArraySorted(A)) return true;

     for (var i = 0; i < A.length; i++) //if not sorted lets check
     {
         for (var j = i + 1; j < A.length; j++) {
             if (A[i] > A[j]) //swap only if A[i] > A[j]
             {
                 var temp = A[i];
                 A[i] = A[j];
                 A[j] = temp;
                 return isArraySorted(A); // after one swap check if it's sorted and return that value.
             }
         }
     }
 }
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
  • got it. However for this test case [1, 5, 3, 3, 7] it would get False and should be true what do you think ? – Mozein May 02 '15 at 06:24
  • I've edited. The new edit will return true if the array is sorted or if one swapping sorted the array. Otherwise it will return false. – Amir Popovich May 02 '15 at 06:28
  • this should return true because if we make one swap only, like the second 3 and 5, it will become sorted. so should return true.. – Mozein May 02 '15 at 06:30