Skip to content

‌插入排序(Insertion Sort)

插入排序(Insertion Sort)

插入排序是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。

示例

3
5
7
8
4
1
6
9
2

点我排序

vue
<script setup lang="ts">
  import {reactive} from "vue";
  const binsertionSortList = reactive({
    binsertionSortList:[3,5,7,8,4,1,6,9,0]
  })
  const binsertionSortClick= ()=>{
    insertionSort(binsertionSortList.binsertionSortList)
  }
  function insertionSort(arr) {
    let n = arr.length;
    for (let i = 1; i < n; i++) {
      let key = arr[i];
      let j = i - 1;
      while (j >= 0 && arr[j] > key) {
        arr[j + 1] = arr[j];
        j--;
      }
      arr[j + 1] = key;
    }
    return arr;
  }
</script>

<template>
  <p>{{JSON.stringify(binsertionSortList.binsertionSortList)}}</p>
  <h4 @click="binsertionSortClick">点我排序</h4>
</template>

<style scoped lang="scss">

</style>

不知道说啥了很无语了