排序和搜索
定义





排序算法
冒泡排序

code
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]){
let temp = this[j];
this[j] = this[j+1];
this[j+1] = temp;
}
}
}
}
const arr = [5, 4, 3, 2, 1]
arr.bubbleSort();
时间复杂度

选择排序

code
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;
}
}
}
}
const arr = [5, 4, 3, 2, 1]
arr.selectionSort();
时间复杂度

插入排序

code
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--;
}
this[j] = temp;
}
}
const arr = [5, 4, 3, 2, 1]
arr.insertionSort();
时间复杂度
