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

时间:2015-04-27 09:10:18

标签: javascript html algorithm bubble-sort

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

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

程序似乎陷入无限循环,因为'另一个传递'反复打印到控制台。按照此行console.log("Another pass");

的指示

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

为什么函数没有交换数组中术语的索引?

(代码似乎无法在SO&#39的代码段工具上正常运行,可能必须复制到记事本文档中)



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();
}
&#13;
<head>
</head>
<body onload="main()">
</body>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您的代码中有错误:

if (ii = len) {

以及

if (swapped = 1){ 

它应该是双重等于

答案 1 :(得分:1)

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

if (ii = len)&amp; if (swapped = 1)应该有=====运营商。这导致了无限循环。

  

注意:根据避免全局变量的最佳做法,您的代码不合适。你不应该使用全局变量并尝试   传递变量并在处理后将它们返回。

请参阅this以避免全局变量。

相关问题