冒泡排序
最大值向後冒泡
複製代碼
Array.prototype.bubblesSort = 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]){
let temp = this[j];
this[j] = this[j + 1];
this[j + 1] = temp;
}
}
}
};
const arr = [5,4,3,2,1,0];
arr.bubblesSort();
複製代碼
選擇排序
最小值排第一位、第二小值排第二位。以此類推
複製代碼
Array.prototype.selectionSort = function () {
for (let i = 0; i < this.length - 1; i++) {
let indexMin = i;
for (let j = i; j < this.length; j++) {
if (this[j] < this[indexMin]) {
indexMin = j;
}
}
if (indexMin !== i){
const temp = this[i];
this[i] = this[indexMin];
this[indexMin] = temp;
}
}
console.log(this);
};
const arr = [5,2, 4, 3, 2, 1];
arr.selectionSort();
複製代碼
插入排序
從第二個數開始往前比、比它大就日後排
複製代碼
Array.prototype.insertionSort = function () {
for (let i = 1; i < this.length; i++){
const temp = this[i];
let j = i;
while (j > 0){
if (this[j - 1] > temp){
this[j] = this[j - 1];
} else {
break;
}
j -= 1;
}
this[j] = temp;
}
console.log(this);
};
const arr = [5,4,3,2,1,0];
arr.insertionSort();
複製代碼
快速排序
分區而後排序、性能較好、能夠項目中使用
複製代碼
Array.prototype.quickSort = function () {
const rec = (arr) => {
if (arr.length === 1) {return arr}
let left = [];
let right = [];
const mid = arr[0];
for (let i = 1; i < arr.length; i++){
if (arr[i] < mid){
left.push(arr[i])
} else {
right.push(arr[i]);
}
}
return [...rec(left), mid, ...rec(right)];
};
const res = rec(this);
res.forEach((n,i) => {
this[i] = n
});
console.log(this);
};
const arr = [2,4,5,3,1];
arr.quickSort();
複製代碼