Use radix sort base sort to sort the numbers, specify the base sort implementation of the base

The concept of base sort is not explained. The point to be said is that the base in base sort can be selected arbitrarily, but most of the radix sort codes on the Internet use 10 as the base, and my code is OK Arbitrarily specify the base, the code is as follows:

import random
def numerical_radix_sort(num_list, b):
    maxmium = num_list[0]
    for i in num_list:
        if maxmium < i:
            maxmium = i
    print(maxmium)
    exp_base = 1
    while maxmium > b ** exp_base:
        exp_base = exp_base + 1

    i = 0
    while i < exp_base:
        bucket = {}
        for x in range(b):
            bucket[x] = []

        for x in num_list:
            radix = int( (x/b**i) ) % b
            bucket[radix].append(x)

        j = 0
        for k in range(b):
            if(len(bucket[k])) != 0:
                for y in bucket[k]:
                    num_list[j] = y
                    j = j + 1

        i = i + 1
    return num_list

###下面的代码是测试代码

num_list = [random.randint(0,100) for _ in range(20)]
base = 16
print(num_list)
num_list = numerical_radix_sort(num_list,base)
print(num_list)

The running result is:

[9, 19, 86, 11, 1, 47, 17, 13, 70, 51, 82, 18, 39, 39, 43, 75, 72, 26, 29, 100]
100
[1, 9, 11, 13, 17, 18, 19, 26, 29, 39, 39, 43, 47, 51, 70, 72, 75, 82, 86, 100]

 

Guess you like

Origin blog.csdn.net/t20134297/article/details/108150387