Javascript将数组传递给类中的函数

时间:2017-11-08 20:36:01

标签: javascript arrays sorting

请让我知道,为什么我的功能不起作用,

class sort{

constructor(array){

  this.array=array;
}

/* Buble soring */
  bubble_sort(){

      let swapped = false;


      for(let i=0; i<this.array.length; i++){
            if(this.array[i]>this.array[i+1]){
              /* Swapping method */
              let temp = this.array[i+1];
              this.array[i] = this.array[i];
              this.array[i] = this.array[i+1];
              this.array[i+1] =temp;
              return this.array;
            };
      };

  };
};


let d = new sort([5,4,3,2,1]);

console.log(d.bubble_sort())

1 个答案:

答案 0 :(得分:0)

以下代码可以使其成为一个冒泡排序,你需要2个循环。通过一个循环,您基本上只需对第一个数字进行排序。

class sort {
  constructor(array) {
    this.array = array;
  }

  /* Buble soring */

  bubble_sort() {
    let swapped = false;

    for (let i = 0; i < this.array.length; i++) {
      if (this.array[i] > this.array[i + 1]) {
        /* Swapping method */
        let temp = this.array[i + 1];
        this.array[i + 1] = this.array[i];
        this.array[i] = temp;
      }
    }
    return this.array;
  }
}

let d = new sort([5, 4, 3, 2, 1]);

console.log(d.bubble_sort());