MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / pigeonhole_sort

Function pigeonhole_sort

sorts/pigeonhole_sort.py:6–39  ·  view source on GitHub ↗

>>> a = [8, 3, 2, 7, 4, 6, 8] >>> b = sorted(a) # a nondestructive sort >>> pigeonhole_sort(a) # a destructive sort >>> a == b True >>> pigeonhole_sort([])

(a)

Source from the content-addressed store, hash-verified

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
12 True
13
14 >>> pigeonhole_sort([])
15 """
16 if not a:
17 return
18 # size of range of values in the list (ie, number of pigeonholes we need)
19
20 min_val = min(a) # min() finds the minimum value
21 max_val = max(a) # max() finds the maximum value
22
23 size = max_val - min_val + 1 # size is difference of max and min values plus one
24
25 # list of pigeonholes of size equal to the variable size
26 holes = [0] * size
27
28 # Populate the pigeonholes.
29 for x in a:
30 assert isinstance(x, int), "integers only please"
31 holes[x - min_val] += 1
32
33 # Putting the elements back into the array in an order.
34 i = 0
35 for count in range(size):
36 while holes[count] > 0:
37 holes[count] -= 1
38 a[i] = count + min_val
39 i += 1
40
41
42def main():

Callers 1

mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected