冒泡排序算法无法正常工作(javascript)

时间:2018-04-08 21:33:28

标签: javascript algorithm bubble-sort

好的,我的泡泡排序算法存在这个奇怪的问题。它会像它应该的那样向右移动一段时间,但它会突然停在中间位置并向左移动较小的数字而不是向右移动。这是在P5.js中完成的,但我不确定这是不是问题。

我真的很困惑,因为这是一个简单的算法,我让它在python中工作。

代码:

let arr3 = [90, 10, 40, 70, 5, 30, 20, 60, 80, 50];


function setup(){
  createCanvas(400, 400);
  background(51);
  frameRate(1);
}

function draw(){
  background(51);
  bubbleSort(arr3);   //Initiating Bubble Sort
}

function bubbleSort(a){       //Bubble Sort algorithm
  let run = true;
  while(run){
    run = false;
    for(let i=0; i<a.length-1; i++){
      if(a[i] > a[i+1]){
        let temp = a[i+1];   //Swapping 
        a[i+1] = a[i];
        a[i] = temp;
        run = true;
        console.log(a);      //Printing current array
        return a;
      }
    }
  }
}

输出:

[10, 90, 40, 70, 5, 30, 20, 60, 80, 50]
[10, 40, 90, 70, 5, 30, 20, 60, 80, 50]
[10, 40, 70, 90, 5, 30, 20, 60, 80, 50]
[10, 40, 70, 5, 90, 30, 20, 60, 80, 50] //The 90 should keep going but
[10, 40, 5, 70, 90, 30, 20, 60, 80, 50] //it stops and 5 keep swapping
[10, 5, 40, 70, 90, 30, 20, 60, 80, 50] //with bigger numbers..
[5, 10, 40, 70, 90, 30, 20, 60, 80, 50]
[5, 10, 40, 70, 30, 90, 20, 60, 80, 50]
[5, 10, 40, 30, 70, 90, 20, 60, 80, 50]
[5, 10, 30, 40, 70, 90, 20, 60, 80, 50]
[5, 10, 30, 40, 70, 20, 90, 60, 80, 50]
[5, 10, 30, 40, 20, 70, 90, 60, 80, 50]
[5, 10, 30, 20, 40, 70, 90, 60, 80, 50]
[5, 10, 20, 30, 40, 70, 90, 60, 80, 50]
[5, 10, 20, 30, 40, 70, 60, 90, 80, 50]
[5, 10, 20, 30, 40, 60, 70, 90, 80, 50]
[5, 10, 20, 30, 40, 60, 70, 80, 90, 50]
[5, 10, 20, 30, 40, 60, 70, 80, 50, 90]
[5, 10, 20, 30, 40, 60, 70, 50, 80, 90]
[5, 10, 20, 30, 40, 60, 50, 70, 80, 90]
[5, 10, 20, 30, 40, 50, 60, 70, 80, 90]

1 个答案:

答案 0 :(得分:0)

我对P5.js并不是很熟悉,但是我认为问题只是您放置return语句的地方。您将希望像这样在while循环之外获得最终收益:

function bubbleSort(a){       //Bubble Sort algorithm
  let run = true;
  while(run){
    run = false;
    for(let i=0; i<a.length-1; i++){
      if(a[i] > a[i+1]){
        let temp = a[i+1];   //Swapping 
        a[i+1] = a[i];
        a[i] = temp;
        run = true;
      }
    }
  }
  return a;
}