一、计数排序

概要:  

  时间复杂度O(n),空间复杂度O(k),k是输入序列的值的范围(最大值-最小值),是稳定的。计数排序一般用于已知输入值的范围相对较小,比如给公司员工的身高体重信息排序。

思路:

   输入数组A为{3,5,1,2,4,3},值的范围是1~5,所以创建5个桶,序号1,2,3,4,5。装桶时遍历一遍输入数组,A[0]=3,把它放到3号桶;A[1]=5,放到5号桶;1放到1号桶……最后3放到3号桶。现在三号桶的值为2,其他桶的值为1,再遍历一遍桶数组,按顺序把桶倒出,元素被倒出的顺序就是排序的顺序了。

Python实现:

# coding:utf-8
class CountingSort:
def countingSort(self, A, m):
result = []
A_min = min(A)
A_max = max(A)
buckets_len = A_max - A_min + 1
buckets = [0] * buckets_len # 创建桶
# 装桶
for n in A:
buckets[n-A_min] += 1
# 桶倒出
for i in xrange(buckets_len):
value = i + A_min
n = buckets[i]
result += [value] * n
return result l = [54, 35, 48, 36, 27, 12, 44, 44, 8, 14, 26, 17, 28]
print CountingSort().countingSort(l, len(l))

二、基数排序

思路:

  首先准备0号桶~9号桶:

    

  根据个位上的数值选择几号桶,后再将数字依次倒出桶:

      

  根据序列的顺序十位上的数值选择几号桶,后再将数字依次倒出桶:

      

  根据序列的顺序百位上的数值选择几号桶,后再将数字依次倒出桶,最后一次倒出桶的顺序就是排序的顺序:

      

Python实现:

# -*- coding:utf-8 -*-

class RadixSort:
def radixSort(self, A, n):
order_array = A
buckets = [[] for i in xrange(10)] # 生成桶
radix = 1 # 基数为1代表个位
max_radix = 10 ** len(str(max(order_array))) # 这些数的最大位
while radix < max_radix:
for n in order_array:
digit = (n / radix) % 10 # 个位、十位、百位...
buckets[digit].insert(0, n) # 将数字添加到桶中 i = 0
for pour_nums in buckets:
while pour_nums:
order_array[i] = pour_nums.pop()
i += 1
radix *= 10
return order_array l = [54, 35, 48, 36, 27, 12, 44, 44, 8, 14, 26, 17, 28]
print RadixSort().radixSort(l, len(l))

最新文章

  1. Blog List
  2. lex中yyrestart()的使用
  3. IOS开发_中遍历数组的方法及比较
  4. interactivePopGestureRecognizer属性
  5. 3D Touch集成过程整理
  6. 19.Android之文件存储方法学习
  7. 阻塞与非阻塞的IO网络读写
  8. C#调用C++ DLL类方法(转)
  9. cssradius
  10. webpack学习(七)打包压缩图片
  11. thinkphp框架,数据动态缓存后,或数据已读取出来,想分页怎么办
  12. git常用命令学习笔记
  13. Mysql 允许远程连接
  14. ios webview调试
  15. 5分钟搭建 nginx +php --------------(LNMP)新手专用
  16. Git -- 工作区 和 暂存区
  17. u3d静态函数
  18. 求字符串长度StringLength();
  19. luoguP4492 [HAOI2018]苹果树 组合计数 + dp
  20. 批量合并GDB

热门文章

  1. 011-HQL中级1-Hive快捷查询:不启用Mapreduce job启用Fetch task三种方式介绍
  2. html5游戏开发-零基础开发《圣诞老人送礼物》小游戏
  3. 宏表达式与函数、#undef、条件编译、
  4. gdb core
  5. Java设计原则—里氏替换原则(转)
  6. MySQL 温故知心(二) 事务的隔离级别
  7. 88. Merge Sorted Array(从后向前复制)
  8. react-native 解决Could not find method android() for arguments问题
  9. Ubuntu16.04 Docker 安装
  10. java内存空间