Variable Digit Count Sort.

Θ(n) where n is the total digit count

from random import choices

def countingSort(source:[], digits:[], scope:int) -> []:
    counter = [0]*scope
    amount = len(source)

    for x in digits:
        counter[x] += 1

    for i in range(1, scope):
        counter[i] += counter[i-1]

    destination = [0]*amount

    for i in reversed(range(amount)):
        quantity = digits[i]
        # index = count-1
        destination[counter[quantity]-1] = source[i]
        counter[quantity] -= 1

    return destination

def radixSort(source:[], numOfDigits:int, scope:int)->[]:
    amount = len(source)
    dst = source
    for i in range(numOfDigits):
        digits = []
        for x in dst:
            temp = x // (scope ** i)
            digit = temp % scope
            digits.append(digit)
        dst = countingSort(dst, digits, scope)
    return dst

def digitCountOfFigure(figure:int)->int:
    if figure == 0:
        return 1
    count = 0
    while figure != 0:
        count += 1
        figure //= 10
    return count

def variableDigitCountSort()->[]:
    scope = 10
    amount = 1000
    digits = 3
    src = choices(range(amount), k=amount)
    groups = [[] for _ in range(digits)]

    for x in src:
        groups[digitCountOfFigure(x) - 1].append(x)
        
    dst = []
    for i in range(digits):
        dst += radixSort(groups[i], i+1, scope)
    return dst
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,196评论 0 10
  • 解开你的红肚带 洒一床雪花白 普天下所有的水 都在你眼里荡开 这是周云蓬《不会说话的爱情》中的一段歌词,也是他最富...
    哲道禅者阅读 4,398评论 5 0
  • 一场电影像极了我们的一生 纷繁的镜头里是不同的我们 场景里,时间的沙漏总是在最显眼的位置 十年,二十年,许多年,每...
    夏无知阅读 1,319评论 0 1
  • 古人云:书中自有黄金屋,书中自有颜如玉”。书房已经成为现代家庭必备的活动空间,但现在房价越来越高,书房的面积也是有...
    日光独倾城却少了旧人阅读 1,792评论 0 1
  • 《灵枢·寒热病》:足太阳有通项入脑者,正属目本,名曰眼系。。。在项中两筋间,入脑乃别阴跷、阳跷,阴阳相交,。。。交...
    李伟需阅读 6,174评论 0 1

友情链接更多精彩内容