How to find the Minimum number of swaps required for sorting an array of numbers in descending order in javascript

前端 未结 1 1112
攒了一身酷
攒了一身酷 2021-01-14 00:35

I\'m trying to get my code to do this:

Original array = [1,2,3,4] swap once-> [4,2,3,1] swap again->[4,3,2,1]

Therefore result is 2

But it\'s not wo

相关标签:
1条回答
  • 2021-01-14 01:08

    I would start with a copy of the array in descending order for getting the right index of the items.

    For practical reasons, (or just a shorter conception of the loop with including check and decrement), I loop from the end of the array.

    Then I check the value of array and reversed at the dame index and go on with the iteration.

    If not the same value, the items at the wanted position i and the actual position p are swapped and the count incremented.

    At the end the count is returned.

    function check(array) {
      var reversed = array.slice().sort((a, b) => b - a),
          count = 0,
          i = array.length,
          p;
    
      while (i--) {
          if (array[i] === reversed[i]) continue;
          p = array.indexOf(reversed[i]);
          [array[i], array[p]] = [array[p], array[i]];
          count++;
      }
      console.log(...array);
      return count;
    }
    
    console.log(check([1, 2, 3, 4, 5, 6])); // 3
    console.log(check([6, 5, 4, 3, 2, 1])); // 0
    console.log(check([1, 2, 3, 4])); // 2
    console.log(check([1, 3, 2, 5, 4, 6])); // 3
    console.log(check([1, 2, 10, 4, 5, 6, 7, 8, 9, 3, 12, 11])); // 6
    console.log(check([ 49, 37, 9, 19, 27, 3, 25, 11, 53,  42, 57, 50, 55,  56, 38, 48, 6, 33, 28, 8, 20, 31, 51, 14, 23, 4, 58, 52, 36, 22, 41, 47, 39, 2, 7, 13, 45, 1, 44, 32, 10, 15, 21, 30, 17,  60, 29, 5, 59, 12, 40, 24, 54, 46, 26, 43, 35, 34, 18, 16])); // 54
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
提交回复
热议问题