冒泡排序不交换 Javascript 中的数组元素

Bubble sort not swapping elements of array in Javascript

我正在创建一个简单的程序,它应该利用冒泡排序算法按升序对数字列表进行排序。

出于测试目的,我添加了行 alert(unsortedNumbers);,如果您 运行 它,您会看到,无论算法通过多少次,数字都不会改变顺序。

程序似乎陷入了无限循环,因为 'Another pass' 重复打印到控制台。按照此行的指示 console.log("Another pass");

与冒泡排序算法一样,一旦它不必在某个传递上交换任何项,我们就知道这是排序列表,我创建了变量swapped,但是它看起来像这样总是 1。我认为这可能是由于 swapArrayElements() 函数没有交换术语造成的。

为什么函数不交换数组中项的索引?

(代码在 SO 的代码片段工具上似乎 运行 不正确,可能需要复制到记事本文档中)

function main(){

  var unsortedNumbers =[7,8,13,1,6,9,43,80]; //Declares unsorted numbers array
  alert(unsortedNumbers);
  var swapped = 0;
  var len = unsortedNumbers.length;

  function swapArrayElements(index_a, index_b) { //swaps swapArrayElements[i] with swapArrayElements[ii]
    var temp = unsortedNumbers[index_a];
    unsortedNumbers[index_a] = unsortedNumbers[index_b];
    unsortedNumbers[index_b] = temp;
  }

  function finish(){
    alert(unsortedNumbers);
  }

  function mainBody(){
    for(var i =0;i<len;i++){
      var ii =(i+1);
      if (unsortedNumbers[i]>unsortedNumbers[ii]){
        console.log("Swap elements");
        swapArrayElements(i,ii);
        swapped=1; // Variable 'swapped' used to check whether or not a swap has been made in each pass
      }
      if (ii = len){
        if (swapped = 1){ // if a swap has been made, runs the main body again
          console.log("Another pass");
          alert(unsortedNumbers); //Added for debugging
          swapped=0;
          mainBody();
        }else{
          console.log("Finish");
          finish();
        }
      }
    }
  }



  mainBody();
}
<head>
</head>
<body onload="main()">
</body>

您的代码有误:

if (ii = len) {

还有

if (swapped = 1){ 

应该是双等号

导致无限循环的无效条件检查:

if (ii = len) & if (swapped = 1) 应该有 ===== 运算符。这导致了无限循环。

NOTE: Your code is not appropriate as per the best practices to avoid global variables. You should not use global variables and try passing variables and returning them back after processing.

参考 this 避免全局变量。