Skip to content

计数排序(Counting Sort)‌

计数排序(Counting Sort)‌

计数排序是一个线性时间复杂度的排序算法。它的基本思想是通过统计每一个数的出现次数,然后根据这些统计数字将序列中的元素排好序。

示例

10
3
5
7
8
4
1
6
9
2

点我排序

vue
<script setup lang="ts">
  import {reactive} from "vue";
  const CountingSortList = reactive({
    CountingSortList:[66,3,5,7,8,4,1,6,9,0]
  })

  const CountingSortClick= ()=>{
    console.log()
    CountingSortList.CountingSortList=countingSort([...CountingSortList.CountingSortList])
  }


  function countingSort(arr) {
    if (arr.length <= 1) {
      return arr;
    }
    let min = arr[0];
    let max = arr[0];
    for (let i = 1; i < arr.length; i++) {
      if (arr[i] < min) {
        min = arr[i];
      } else if (arr[i] > max) {
        max = arr[i];
      }
    }
    let count = new Array(max - min + 1).fill(0);
    for (let i = 0; i < arr.length; i++) {
      count[arr[i] - min]++;
    }
    let sortedIndex = 0;
    for (let i = 0; i < count.length; i++) {
      while (count[i] > 0) {
        arr[sortedIndex] = i + min;
        sortedIndex++;
        count[i]--;
      }
    }
    return arr;
  }
</script>
<template>
  <p>{{JSON.stringify(CountingSortList.CountingSortList)}}</p>
  <h4 @click="CountingSortClick">点我排序</h4>
</template>
<style scoped lang="scss">
</style>

不知道说啥了很无语了