数据结构-排序和搜索


排序和搜索

定义

定义

定义

排序算法

搜索算法4

排序算法

冒泡排序

code

Array.prototype.bubbleSort = function(){
  // console.log(this);  // (5) [5, 4, 3, 2, 1]
  for(let i = 0; i < this.length - 1; i++){		    // 循环n-1轮
    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();

时间复杂度

时间复杂度


文章作者: Zetai Wei
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Zetai Wei !
评论
  目录