Skip to content

Commit 82500ba

Browse files
author
Liam
committed
add pigeonhole sort
1 parent 20c1c4e commit 82500ba

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,7 @@ If you want to uninstall algorithms, it is as simple as:
277277
- [meeting_rooms](algorithms/sort/meeting_rooms.py)
278278
- [merge_sort](algorithms/sort/merge_sort.py)
279279
- [pancake_sort](algorithms/sort/pancake_sort.py)
280+
- [pigeonhole_sort](algorithms/sort/pigeonhole_sort.py)
280281
- [quick_sort](algorithms/sort/quick_sort.py)
281282
- [radix_sort](algorithms/sort/radix_sort.py)
282283
- [selection_sort](algorithms/sort/selection_sort.py)

algorithms/sort/pigeonhole_sort.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
3+
https://en.wikipedia.org/wiki/Pigeonhole_sort
4+
5+
Time complexity: O(n + Range) where n = number of elements and Range = possible values in the array
6+
7+
Suitable for lists where the number of elements and key values are mostly the same.
8+
9+
"""
10+
11+
12+
def pigeonhole_sort(arr):
13+
Max = max(arr)
14+
Min = min(arr)
15+
size = Max - Min + 1
16+
17+
holes = [0]*size
18+
19+
for i in arr:
20+
holes[i-Min] += 1
21+
22+
i = 0
23+
for count in range(size):
24+
while holes[count] > 0:
25+
holes[count] -= 1
26+
arr[i] = count + Min
27+
i += 1
28+
return arr

tests/test_sort.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
insertion_sort,
1010
merge_sort,
1111
pancake_sort,
12+
pigeonhole_sort,
1213
quick_sort,
1314
selection_sort,
1415
bucket_sort,
@@ -70,6 +71,10 @@ def test_merge_sort(self):
7071
def test_pancake_sort(self):
7172
self.assertEqual([1, 5, 23, 57, 65, 1232],
7273
pancake_sort([1, 5, 65, 23, 57, 1232]))
74+
75+
def test_pigeonhole_sort(self):
76+
self.assertEqual([1, 5, 23, 57, 65, 1232],
77+
pigeonhole_sort([1, 5, 65, 23, 57, 1232]))
7378

7479
def test_quick_sort(self):
7580
self.assertEqual([1, 5, 23, 57, 65, 1232],

0 commit comments

Comments
 (0)