LSD - 基数排序

LSD - 基数排序_第1张图片

实现方法

  • MSD(Most Significant Digit first,最高位优先法): 从高位起。
  • LSD(Least Significant Digit first,最低位优先法):从低位起。

这里采用LSD

  • data
    • 确定基数radix (这里为10,桶的个数)
    • 确定位数 (需要做分桶的次数,即循环的次数)
    • array 即输入,要排序的数组
  • logic
    • 分桶
    • 合并
def radix_sort(array):
        merge_bucket = array
        bucket =  [[] for i in range(10)]
        maxbit = 1
        
        for item in array:
            while item["#pos"] > pow(10,maxbit):
                maxbit += 1

        for loop_time in range(maxbit):
            bucket = [[] for i in range(10)]
            for item in merge_bucket:
                bucket[pointed_bit(item["#pos"],loop_time)].append(item)
            merge_bucket = []
            for i in range(10):
                merge_bucket.extend(bucket[i])

        return merge_bucket
# 对齐两个数组
base=[{"a":1},{"a":5},{"a":2}]
new= [{"a":1},{"a":3},{"a":2}]
def pointed_bit(num, digit):
    # 取指定位的值
    # 112 取个位 poinited_bit(112,0)
    return num % pow(10,digit+1) / pow(10,digit)

def radix_sort(array_base, array_new, sort_key):
    # Use for [{"#pos":1,.pri..},{}]
    # sort_key: "#pos"
    merge_bucket_new = array_new
    merge_bucket_base = array_base
    # 位数, 排序次数
    maxbit = 1
    for item in array_new:
        while item[sort_key] > pow(10,maxbit):  
        	maxbit += 1
    for loop_time in range(maxbit):
        bucket_new = [[] for i in range(10)]
        bucket_base = [[] for i in range(10)]
        for index in range( len(merge_bucket_new) ):
            place_new = pointed_bit(merge_bucket_new[index][sort_key],loop_time)
            bucket_new[place_new].append(merge_bucket_new[index])
            place_base = pointed_bit(merge_bucket_base[index][sort_key],loop_time)
            bucket_base[place_base].append(merge_bucket_base[index])
        merge_bucket_base = []
        merge_bucket_new  = []
        for i in range(10):
            merge_bucket_base.extend(bucket_base[i])
            merge_bucket_new.extend(bucket_new[i])
    return merge_bucket_base,merge_bucket_new



print base
print new

print a
print b

python 语法

  • array = [[]] * 10 此时id(array[0])==id(array[1]) #shallow copy
    应使用 array = [ [] for i in range(10)]

你可能感兴趣的:(简单算法)