TheAlgorithms-Python
45 строк · 1.1 Кб
1# Python program to implement Pigeonhole Sorting in python
2
3# Algorithm for the pigeonhole sorting
4
5
6def pigeonhole_sort(a):7"""8>>> a = [8, 3, 2, 7, 4, 6, 8]
9>>> b = sorted(a) # a nondestructive sort
10>>> pigeonhole_sort(a) # a destructive sort
11>>> a == b
12True
13"""
14# size of range of values in the list (ie, number of pigeonholes we need)15
16min_val = min(a) # min() finds the minimum value17max_val = max(a) # max() finds the maximum value18
19size = max_val - min_val + 1 # size is difference of max and min values plus one20
21# list of pigeonholes of size equal to the variable size22holes = [0] * size23
24# Populate the pigeonholes.25for x in a:26assert isinstance(x, int), "integers only please"27holes[x - min_val] += 128
29# Putting the elements back into the array in an order.30i = 031for count in range(size):32while holes[count] > 0:33holes[count] -= 134a[i] = count + min_val35i += 136
37
38def main():39a = [8, 3, 2, 7, 4, 6, 8]40pigeonhole_sort(a)41print("Sorted order is:", " ".join(a))42
43
44if __name__ == "__main__":45main()46