python算法学习之计数排序实例

yipeiwu_com6年前Python基础

python算法学习之计数排序实例

复制代码 代码如下:

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

def _counting_sort(A, B, k):
    """计数排序,伪码如下:
    COUNTING-SORT(A, B, k)
    1  for i ← 0 to k // 初始化存储区的值
    2    do C[i] ← 0
    3  for j ← 1 to length[A] // 为各值计数
    4    do C[A[j]] ← C[A[j]] + 1
    5  ▷ C[i]包含等于i的元素个数
    6  for i ← 1 to k // 求计数和,确定<=各值的元素数
    7    do C[i] ← C[i] + C[i-1]
    8  ▷ C[i]包含小于或等于i的元素个数
    9  for j ← length[A] downto 1
    10   do B[C[A[j]]] ← A[j] // 将A[j]值放到对应位置
    11      C[A[j]] ← C[A[j]] - 1 // 避免元素相同时覆盖同一位置

    T(n) = θ(n)

    Args:
        A (Sequence): 原数组
        B (Sequence): 结果数组
        k (int): 值上限,假定了所有元素介于[0,k]
    """
    len_c = k + 1
    C = [0] * len_c
    for a in A:
        C[a] = C[a] + 1
    for i in range(1, len_c):
        C[i] = C[i] + C[i-1]
    for a in A[::-1]:
        B[C[a]-1] = a
        C[a] = C[a] - 1

def counting_sort(A):
    """假定A数组所有元素都介于[0,len(A)-1]"""
    B = [0] * len(A)
    _counting_sort(A, B, len(A) - 1)
    return B

if __name__ == '__main__':
    import random, timeit

    items = range(10000)
    random.shuffle(items)

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

    def test_counting_sort():
        print(items)
        sorted_items = counting_sort(items)
        print(sorted_items)

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

相关文章

在numpy矩阵中令小于0的元素改为0的实例

如下所示: >>> import numpy as np >>> a = np.random.randint(-5, 5, (5, 5)) >...

python实现ipsec开权限实例

本文实例讲述了python实现ipsec开权限的方法。分享给大家供大家参考。具体实现方法如下: windows自带的命令行工具netsh ipsec static add filter不...

解决Python3用PIL的ImageFont输出中文乱码的问题

解决Python3用PIL的ImageFont输出中文乱码的问题

今天在用python3+ImageFont输出中文时,结果显示乱码 # coding:utf-8 from PIL import Image, ImageDraw, ImageFon...

Django ORM框架的定时任务如何使用详解

Django ORM框架的定时任务如何使用详解

前言 大家在Django项目开发过程中,是不是也经常遇到这样的场景:需要实现一个定时任务,但又不想脱离Django环境独立运行,如:还需要使用Django的ORM框架操作Models类、...

Python实现的简单发送邮件脚本分享

近来有些东西需要监控报警发邮件,然后在网上找了点材料,自己写了一个简单发送邮件的脚本,主要就是运用python的smtplib模块,分享给大家看一下: 复制代码 代码如下: #!/usr...