Array.prototype.bubbleSort = function () {
for (let i = 0; i < this.length - 1; i += 1) { // 控制比较次数,共n-1次
for (let j = 0; j < this.length - 1 - i; j += 1) { // 控制相邻元素进行比较
if (this[j] > this[j + 1]) {
const temp = this[j];
this[j] = this[j + 1];
this[j + 1] = temp;
}
}
}
};
const arr = [5, 4, 3, 2, 1];
arr.bubbleSort();
文章永久链接:https://fe8.cn/question/629cd1352d155
原理