Fancy DSA Fancy DSA
数据结构
算法
LeetCode
  • 关于
  • 导航 (opens new window)
  • 分类
  • 标签
  • 归档
设计模式 (opens new window)
博客 (opens new window)
GitHub (opens new window)

Jonsam NG

想的更多,也要想的更远
数据结构
算法
LeetCode
  • 关于
  • 导航 (opens new window)
  • 分类
  • 标签
  • 归档
设计模式 (opens new window)
博客 (opens new window)
GitHub (opens new window)
  • 开始上手
  • Plan 计划
  • Roadmap 路线
  • 算法简介
  • Sort 排序

    • 章节概要
    • AlphaNumericalSort [字母顺序排序]
    • BeadSort [珠排序]
    • BogoSort [Bogo 排序]
    • BubbleSort [冒泡排序]
    • BucketSort [桶排序]
    • CocktailShakerSort [鸡尾酒排序]
    • CombSort [梳排序]
    • CountingSort [计数排序]
    • CycleSort [圈排序]
    • FisherYatesShuffle [洗牌算法]
    • FlashSort [闪电排序]
    • GnomeSort [侏儒排序]
    • HeapSort [堆排序]
    • InsertionSort [插入排序]
    • IntroSort [内省排序]
    • MergeSort [归并排序]
    • OddEvenSort [奇偶排序]
    • PancakeSort [煎饼排序]
    • PigeonHoleSort [鸽巢排序]
      • 介绍
      • 实现
      • 参考
    • QuickSort [快速排序]
    • RadixSort [基数排序]
    • SelectionSort [选择排序]
    • ShellSort [希尔排序]
    • TimSort [Tim 排序]
    • TopologicalSorter [拓扑排序器]
    • WiggleSort [摆动排序]
  • Search 搜索

  • Recursive 递归

  • Graph 图

  • Tree 树

  • Math 数学

  • Hash 哈希

  • String 字符串

  • BitManipulation 位操纵

  • Backtracking 回溯

  • DynamicProgramming 动态规划

  • Cache 缓存

  • Array 数组

  • Ciphers 密码学

  • Conversions 转换

  • ProjectEuler 欧拉计划

  • 其他

  • 算法
  • Sort 排序
jonsam
2022-04-26
目录

PigeonHoleSort [鸽巢排序]

# 介绍

鸽巢排序(Pigeonhole sort),也被称作基数分类,是一种时间复杂度为 O(n){\displaystyle O(n)}O(n) 且在不可避免遍历每一个元素并且排序的情况下效率最好的一种排序算法。但它只有在差值(或者可被映射在差值)很小的范围内的数值排序的情况下实用.

当涉及到多个不相等的元素,且将这些元素放在同一个 “鸽巢” 的时候,算法的效率会有所降低。为了简便和保持鸽巢排序在适应不同的情况,比如两个在同一个存储桶中结束的元素必然相等

我们一般很少使用鸽巢排序,因为它很少可以在灵活性,简便性,尤是速度上超过其他排序算法。事实上,桶排序较鸽巢排序更加的实用。

# 实现

# JavaScript

/*
https://en.wikipedia.org/wiki/Pigeonhole_sort
*Pigeonhole sorting is a sorting algorithm that is suitable
* for sorting lists of elements where the number of elements
* (n) and the length of the range of possible key values (N)
* are approximately the same.
 */
function pigeonHoleSort (arr) {
  let min = arr[0]
  let max = arr[0]

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > max) { max = arr[i] }
    if (arr[i] < min) { min = arr[i] }
  }

  const range = max - min + 1
  const pigeonhole = Array(range).fill(0)

  for (let i = 0; i < arr.length; i++) {
    pigeonhole[arr[i] - min]++
  }

  let index = 0

  for (let j = 0; j < range; j++) {
    while (pigeonhole[j]-- > 0) {
      arr[index++] = j + min
    }
  }
  return arr
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

# 参考

  • 鸽巢排序 - 维基百科,自由的百科全书 (opens new window)
编辑 (opens new window)
上次更新: 2022/05/09, 13:34:14
PancakeSort [煎饼排序]
QuickSort [快速排序]

← PancakeSort [煎饼排序] QuickSort [快速排序]→

最近更新
01
0-20题解
10-31
02
本章导读
10-31
03
算法与转换:Part1
10-28
更多文章>
Theme by Vdoing | Copyright © 2022-2022 Fancy DSA | Made by Jonsam by ❤
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式