Skip to content

Commit a2ee788

Browse files
Create pigeonhole_sorting.py
1 parent 20e9877 commit a2ee788

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Python program to implement Pigeonhole Sorting in python
2+
3+
#Algorithm for the pigeonhole sorting
4+
5+
def pigeonhole_sort(a):
6+
# size of range of values in the list (ie, number of pigeonholes we need)
7+
8+
min_val = min(a) # min()finds the minimum value
9+
max_val = max(a) # max() finds the maximum value
10+
11+
size = max_val - min_val + 1 # size is difference of max and min values plus one
12+
13+
# list of pigeonholes of size equal to the variable size
14+
holes = [0] * size
15+
16+
# Populate the pigeonholes.
17+
for x in a:
18+
assert type(x) is int, "integers only please"
19+
holes[x - min_val] += 1
20+
21+
# Putting the elements back into the array in an order.
22+
i = 0
23+
for count in range(size):
24+
while holes[count] > 0:
25+
holes[count] -= 1
26+
a[i] = count + min_val
27+
i += 1
28+
29+
def main():
30+
31+
a = [8, 3, 2, 7, 4, 6, 8]
32+
print("Sorted order is : ", end = ' ')
33+
34+
pigeonhole_sort(a)
35+
36+
for i in range(0, len(a)):
37+
print(a[i], end = ' ')
38+
39+
if __name__ == '__main__':
40+
main()

0 commit comments

Comments
 (0)