algorithm - Javascript check if list is sorted after one swap - Stack Overflow

I want to check if a list can be sorted by performing at most one swap operation, and I want to return

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 ?

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 ?

Share Improve this question edited May 2, 2015 at 21:17 Mozein asked May 2, 2015 at 6:13 MozeinMozein 8076 gold badges21 silver badges33 bronze badges 1
  • Wouldn't it just be return (count == A.length - 1 || count == A.length - 3) ? – 000 Commented May 2, 2015 at 6:17
Add a ment  | 

3 Answers 3

Reset to default 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 paring 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;
}

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;

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.
             }
         }
     }
 }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745233532a4617780.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信