1. 冒泡排序
时间复杂度O(n²)
Array.prototype.bubbleSort = function () {
for (let i = 0; i < this.length; i++) {
for (let j = 0; j < this.length - 1 - i; j++) {
if (this[j] > this[j + 1]) {
const temp = this[j];
this[j] = this[j + 1];
this[j + 1] = temp;
}
}
}
return this;
};
const arr = [5, 4, 3, 2, 1];
console.log(arr.bubbleSort());
2. 选择排序
时间复杂度O(n²)
Array.prototype.selectionSort = function () {
for (let i = 0; i < this.length - 1; i++) {
let minIndex = i;
for (let j = i; j < this.length; j++) {
if (this[j] < this[minIndex]) {
minIndex = j;
}
}
if (minIndex !== i) {
const temp = this[i];
this[i] = this[minIndex];
this[minIndex] = temp;
}
}
return this;
};
const arr = [5, 4, 3, 2, 1];
console.log(arr.selectionSort());