1. 程式人生 > 實用技巧 >Python實現計數排序

Python實現計數排序

計數排序:

  1. 時間複雜度為O(n+k)
  2. 空間複雜度為O(n+k)
  3. 穩定性:穩定
  4. n為陣列元素個數,k為資料最大值

計數排序演算法步驟:

  • 計數排序不是比較數值排序,是記錄資料出現次數的一種排序演算法
  • 找出待排陣列中最大值
  • 額外一個數組記錄待排陣列值出現的次數
  • 迴圈列印儲存數值次數的陣列下標值

動畫演示:

python實現:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File        :CountingSort.py
@Description :
@CreatTime   :2020/08/21 09:42:54
@Author      :Yunhgu
@Version     :1.0
''' def countingSort(arr, maxValue): bucketLen = maxValue+1 bucket = [0]*bucketLen for a in arr: if not bucket[a]: bucket[a]=0 bucket[a]+=1 arr.clear() for i in range(len(bucket)): while bucket[i]>0: arr.append(i) bucket[i]
-=1 return arr if __name__ == "__main__": int_list = [1,8,6,5,6,6,8,4,8] c = countingSort(int_list,10) print(c)