冒泡排序
比较所有相邻元素,如果第一个比第二个大,则交换它们。执行n-1轮,则完成排序。
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]){
const temp = this[j]
this[j] = this[j+1]
this[j+1] = temp
}
// console.log(this);
}
console.log(this);
}
}
const arr = [25, 84, 21, 47, 15, 27, 68, 35, 20];
arr.bubbleSort();
快速排序
定基准:从数组中任意选择一个基准(可以是第一个元素);
分区:所有比基准小的元素放在基准前面,比基准大的元素放在基准后面,形成左右两个分区;
递归:递归地对基准前后的数组进行分区。
Array.prototype.quickSort = function(arr){
const res = (arr) => {
if(arr.length <= 1){
return arr;
}
const left = [];
const 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 [...res(left), mid, ...res(right)]
}
console.log(this);
const result = res(this);
console.log(result);
result.forEach((item, i) => {
this[i] = item
})
console.log(this);
}
const arr = [25, 84, 21, 47, 15, 27, 68, 35, 20];
arr.quickSort();
算法的动画效果可以在此处观看:Visualgo.net