forked from prabhupant/python-ds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pigeonhole_sort.py
36 lines (24 loc) · 1017 Bytes
/
pigeonhole_sort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#Pigeonhole sorting is a sorting algorithm that is suitable for sorting lists of elements where the number of elements and the number of possible key values are approximately the same.
#It requires O(n + Range) time where n is number of elements in input array and ‘Range’ is number of possible values in array.
def pigeonhole_sort(a):
my_min = min(a)
my_max = max(a)
size = my_max - my_min + 1
# our list of pigeonholes
holes = [0] * size
# Populate the pigeonholes.
for x in a:
assert type(x) is int, "integers only please"
holes[x - my_min] += 1
# Put the elements back into the array in order.
i = 0
for count in range(size):
while holes[count] > 0:
holes[count] -= 1
a[i] = count + my_min
i += 1
a = [8, 3, 2, 7, 4, 6, 8]
print("Sorted order is : ", end = ' ')
pigeonhole_sort(a)
for i in range(0, len(a)):
print(a[i], end = ' ')