请让我知道,为什么我的功能不起作用,
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())
答案 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());