python算法学习之桶排序算法实例(分块排序)

yipeiwu_com6年前Python基础

复制代码 代码如下:

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

def insertion_sort(A):
    """插入排序,作为桶排序的子排序"""
    n = len(A)
    if n <= 1:
        return A
    B = [] # 结果列表
    for a in A:
        i = len(B)
        while i > 0 and B[i-1] > a:
            i = i - 1
        B.insert(i, a);
    return B

def bucket_sort(A):
    """桶排序,伪码如下:
    BUCKET-SORT(A)
    1  n ← length[A] // 桶数
    2  for i ← 1 to n
    3    do insert A[i] into list B[floor(nA[i])] // 将n个数分布到各个桶中
    4  for i ← 0 to n-1
    5    do sort list B[i] with insertion sort // 对各个桶中的数进行排序
    6  concatenate the lists B[0],B[1],...,B[n-1] together in order // 依次串联各桶中的元素

    桶排序假设输入由一个随机过程产生,该过程将元素均匀地分布在区间[0,1)上。
    """
    n = len(A)
    buckets = [[] for _ in xrange(n)] # n个空桶
    for a in A:
        buckets[int(n * a)].append(a)
    B = []
    for b in buckets:
        B.extend(insertion_sort(b))
    return B

if __name__ == '__main__':
    from random import random
    from timeit import Timer

    items = [random() for _ in xrange(10000)]

    def test_sorted():
        print(items)
        sorted_items = sorted(items)
        print(sorted_items)

    def test_bucket_sort():
        print(items)
        sorted_items = bucket_sort(items)
        print(sorted_items)

    test_methods = [test_sorted, test_bucket_sort]
    for test in test_methods:
        name = test.__name__ # test.func_name
        t = Timer(name + '()', 'from __main__ import ' + name)
        print(name + ' takes time : %f' % t.timeit(1))

相关文章

对Python定时任务的启动和停止方法详解

在python中我们可以使用APScheduler进行定时任务。 APScheduler的具体编码这里就不介绍了。主要说下在终端中启动和停止任务。 一、运行计划任务的python脚本...

浅谈插入排序算法在Python程序中的实现及简单改进

Python实现插入排序的一般范例为: #coding=cp936 #coding=cp936 #插入排序算法 def InsertionSort(A): for j in r...

python安装numpy和pandas的方法步骤

最近要对一系列数据做同比比较,需要用到numpy和pandas来计算,不过使用python安装numpy和pandas因为linux环境没有外网遇到了很多问题就记下来了。首要条件,pyt...

python中OrderedDict的使用方法详解

很多人认为python中的字典是无序的,因为它是按照hash来存储的,但是python中有个模块collections(英文,收集、集合),里面自带了一个子类 OrderedDict,实...

Python 正则表达式匹配字符串中的http链接方法

利用Python正则表达式匹配字符串中的http链接。主要难点是用正则表示出http 链接的模式。 import re pattern = re.compile(r'http[s]&...