Shinkai005
V1
2022/02/12阅读:30主题:红绯
冒泡排序bubblesort
冒泡排序bubbleSort
gif图解
算法思路
-
比较相邻的元素。如果第一个比第二个大,就交换它们两个; -
对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对,这样在最后的元素应该会是最大的数; -
针对所有的元素重复以上的步骤,除了最后一个; -
重复步骤1~3,直到排序完成。
算法实现
Array.prototype.bubbleSort = function () {
for (let i = 0; i < this.length - 1; i++) {
for (let j = 0; j < this.length - 1 - i; j++) {
if (this[j] > this[j + 1]) {
[this[j], this[j + 1]] = [this[j + 1], this[j]];
}
console.log(this[j], this[j + 1])
}
}
console.log(this);
}
const arr = [5, 4, 3, 2, 1];
arr.bubbleSort();
总结
属于入门级别的算法,但是很有趣.特定场合会常用
时间复杂度
O(n^2)
作者介绍
Shinkai005
V1
公众号:深海笔记Shinkai