【问题标题】:Bubble sort not swapping elements of array in Javascript冒泡排序不交换Javascript中的数组元素
【发布时间】:2015-07-05 15:41:45
【问题描述】:

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

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

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

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

为什么该函数不交换数组中术语的索引?

(代码在 SO 的代码 sn-p 工具上似乎无法正常运行,可能需要复制到记事本文档中)

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){ 它应该是双倍的。
  • @jcubic 感谢您发现此问题,您能否将其写为答案,我将标记为最佳答案。
  • @TobyCannon 我认为有更简单的方法来进行冒泡排序.. 不知道它是否符合您的需求.. nczonline.net/blog/2009/05/26/…
  • @JoelAlmeida 感谢乔尔的链接,看起来确实是一种更有效的方法!这只是尝试了解其背后逻辑的第一次修订,我不会研究更有效的编写方法。

标签: javascript html algorithm bubble-sort


【解决方案1】:

您的代码中有错误:

if (ii = len) {

还有

if (swapped = 1){ 

应该是双等号

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-04-04
      • 2015-04-10
      • 1970-01-01
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 1970-01-01
      相关资源
      最近更新 更多