如何找到在JavaScript中按降序对数字数组进行排序所需的最小交换次数

前端之家收集整理的这篇文章主要介绍了如何找到在JavaScript中按降序对数字数组进行排序所需的最小交换次数 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我试图让我的代码做到这一点:

原始数组= [1,2,3,4]交换一次-> [4,1]再次交换-> [4,1]

因此结果是2

但这不起作用.这是我到目前为止的内容

  1. function check(arr){
  2. var sarr = [];
  3. var cnt = 0;
  4. var arrL = arr.length;
  5. // Create a second copy of the array for reference
  6. var arrCopy = [...arr];
  7. for(let i=0; i<arrL;i++){
  8. var maxV = Math.max(...arr);
  9. sarr.push(maxV);
  10. let pos = arr.indexOf(maxV);
  11. // Remove the found number
  12. arr.splice(pos,1);
  13. // Check if the index of the number in the new array is same with the copy,if not then there was a swap
  14. let ai =arrCopy.indexOf(maxV);
  15. let si =sarr.indexOf(maxV);
  16. if (ai !== si && (i+1)!=arrL && pos !== 0){
  17. cnt++;
  18. };
  19. }
  20. console.log(cnt);
  21. }
  22. check([1,4,5,6]);//Result should be 3
  23. check([6,1]); //result should be 0
  24. check([1,4]); //result should be 2
  25. check([1,6]); //result should be 3
  26. check([1,10,6,7,8,9,12,11]);//result should be 6
  27. check([ 49,37,19,27,25,11,53,  42,57,50,55,  56,38,48,33,28,20,31,51,14,23,58,52,36,22,41,47,39,13,45,1,44,32,15,21,30,17,  60,29,59,40,24,54,46,26,43,35,34,18,16]);//result should be 54

有人可以让我知道我在做什么错吗?

最佳答案
我将从降序排列的数组开始,以获得正确的项目索引.

出于实际原因(或者只是循环的较短概念(包括检查和减量)),我从数组末尾开始循环.

然后,我检查array的值并在dame索引处取反,然后继续进行迭代.

如果值不相同,则交换期望位置i和实际位置p上的项目,并增加计数.

最后,返回计数.

  1. function check(array) {
  2. var reversed = array.slice().sort((a,b) => b - a),count = 0,i = array.length,p;
  3. while (i--) {
  4. if (array[i] === reversed[i]) continue;
  5. p = array.indexOf(reversed[i]);
  6. [array[i],array[p]] = [array[p],array[i]];
  7. count++;
  8. }
  9. console.log(...array);
  10. return count;
  11. }
  12. console.log(check([1,6])); // 3
  13. console.log(check([6,1])); // 0
  14. console.log(check([1,4])); // 2
  15. console.log(check([1,6])); // 3
  16. console.log(check([1,11])); // 6
  17. console.log(check([ 49,16])); // 54
  1. .as-console-wrapper { max-height: 100% !important; top: 0; }

猜你在找的JavaScript相关文章