金狮镖局 Design By www.egabc.com

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  """
    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))

标签:
python算法,计数排序

金狮镖局 Design By www.egabc.com
金狮镖局 免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
金狮镖局 Design By www.egabc.com

评论“python算法学习之计数排序实例”

暂无python算法学习之计数排序实例的评论...

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。