基数排序算法-python实现
2015-09-23 11:18
621 查看
#-*- coding: UTF-8 -*- import numpy as np def RadixSort(a): i = 0 #初始为个位排序 n = 1 #最小的位数置为1(包含0) max = np.max(a) #得到带排序数组中最大数 while max/(10**n) > 0: #得到最大数是几位数 n += 1 while i < n: bucket = {} #用字典构建桶 for x in xrange(0,10): bucket.setdefault(x, []) #将每个桶置空 for x in a: #对每一位进行排序 radix =(x / (10**i)) % 10 #得到每位的基数 bucket[radix].append(x) #将对应的数组元素加入到相应位基数的桶中 j = 0 for k in xrange(0, 10): if len(bucket[k]) != 0: #若桶不为空 for y in bucket[k]: #将该桶中每个元素 a[j] = y #放回到数组中 j += 1 i += 1 if __name__ == '__main__': a = np.random.randint(0, 1000, size = 10) print "Before sorting..." print "---------------------------------------------------------------" print a print "---------------------------------------------------------------" RadixSort(a) print "After sorting..." print "---------------------------------------------------------------" print a print "---------------------------------------------------------------"
相关文章推荐
- 归并排序算法-python实现
- 堆排序算法-python实现
- 插入排序算法-python实现
- 冒泡排序算法-Python实现
- 选择排序算法-python实现
- 快速排序算法-python实现
- python字典按照值排序
- python 时间模块小结
- Python科学计算发行版—Anaconda
- Python json.dumps
- 解决 python用 xlsxwrite 向excel 中写入中文字符串变量 报错
- Python环境及robotframework安装
- python中str函数isdigit、isdecimal、isnumeric的区别
- Python 爬虫进阶必须的几步
- Python特殊语法:filter、map、reduce、lambda
- Python yield 使用浅析
- 【Python之旅】第三篇(二):Pickle序列化
- python模拟用户登录某某网
- python encode和decode函数说明
- the file opeartion in python(一)