冒泡排序的思路:
比较所有相邻元素,如果第一个比第二个大,则交换它们
一轮下来,可以保证最后一个数是最大的
执行n - 1轮,就可以完成排序
Array.prototype.bubbleSort = function () {
for (let i = 0; i < this.length - 1; i++) { // 外面的for循环表示n - 1轮
for (let j = 0; j < this.length - 1 - i; j++) { // 里面的for循环是一轮,并且再减上个i,每次循环的个数就少了
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();
冒泡排序
最新推荐文章于 2023-03-14 22:34:07 发布