今天写个插入排序

28 阅读1分钟

记录一下最近写的两种排序,之前都没听过。感觉比较类似,都是以当前元素为基准对之前或之后的元素比较,但是插入会导致之后的元素位置进行移动,操作更多,没有选择排序好,但两者的平均时间复杂度都是O(n²)

插入排序

function insertionSort(arr) {
  for(let i=1;i<arr.length;i++){
    let insertIndex = i;
    for(let j=i-1;j>=0;j--){
      if(arr[i] < arr[j]){
        insertIndex = j
      }else {
        break;
      }
    }
    if(insertIndex !== i){
      const temp = arr[i];
      arr.splice(i,1);
      arr.splice(insertIndex,0,temp);
    }
  }
}

选择排序

function selectSort(arr) {
  let minIndex = 0;
  let startIndex = 0;
  while(startIndex < arr.length) {
    for(let i = startIndex + 1; i < arr.length; i++) {
    
      if(arr[i] < arr[minIndex]) {
       minIndex = i
      }

    }
    if(startIndex !== minIndex){
      let temp = arr[startIndex];
      arr[startIndex] = arr[minIndex];
      arr[minIndex] = temp;
    }
    startIndex++;
    minIndex = startIndex;
  }
}