# Python程序实现鸽巢排序 # 鸽巢排序的算法 def pigeonhole_sort(a): """ >>> a = [8, 3, 2, 7, 4, 6, 8] >>> b = sorted(a) # 非破坏性排序 >>> pigeonhole_sort(a) # 破坏性排序 >>> a == b True """ # 列表中值的范围大小(即,我们需要的鸽巢数量) min_val = min(a) # min() 查找最小值 max_val = max(a) # max() 查找最大值 size = max_val - min_val + 1 # size 是最大值和最小值之差加一 # 大小等于变量 size 的鸽巢列表 holes = [0] * size # 填充鸽巢。 for x in a: assert isinstance(x, int), "仅允许整数" holes[x - min_val] += 1 # 将元素按顺序放回数组。 i = 0 for count in range(size): while holes[count] > 0: holes[count] -= 1 a[i] = count + min_val i += 1 def main(): a = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(a) print("Sorted order is:", " ".join(map(str, a))) if __name__ == "__main__": main()
标签:__,鸽子,val,min,鸽巢,排序,size From: https://www.cnblogs.com/mlhelloworld/p/18001090