1. 程式人生 > 其它 >《演算法導論》@讀書筆記@ 第八章 - 計數排序(包含js版程式碼實現)

《演算法導論》@讀書筆記@ 第八章 - 計數排序(包含js版程式碼實現)

技術標籤:演算法學習演算法資料結構排序演算法javascript演算法導論

啥是計數排序

計數排序有點類似於窮舉的味道,我們把數字中每個數字出現的次數都記錄下來最後只要依次在組合起來。比如下圖 9 出現了兩次 就在陣列中放入兩個9

演算法過程

  1. 獲取陣列中的最大值
  2. 把他們分類整理並記錄每個數字出現的次數
  3. 重新整理輸出陣列

演算法實現

function CountingSort(arr) {
    let len = arr.length;
    let max = Math.max.apply(null, arr);
    let temp = new Array(max + 1).
fill(null); let result = []; for (let i = 0; i < len; i++) { temp[arr[i]] = temp[arr[i]] ? temp[arr[i]] + 1 : 1 } temp.forEach((e, index) => { if (e != null) { for (let i = 0; i < e; i++) { result.push(index) } } }
) return result } module.exports = CountingSort