Skip to content

Commit f6224b2

Browse files
Merge pull request #668 from terror/add-pigeonhole-sort
add pigeonhole sort
2 parents 4ff61dd + dbf0130 commit f6224b2

File tree

4 files changed

+35
-1
lines changed

4 files changed

+35
-1
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,7 @@ If you want to uninstall algorithms, it is as simple as:
279279
- [meeting_rooms](algorithms/sort/meeting_rooms.py)
280280
- [merge_sort](algorithms/sort/merge_sort.py)
281281
- [pancake_sort](algorithms/sort/pancake_sort.py)
282+
- [pigeonhole_sort](algorithms/sort/pigeonhole_sort.py)
282283
- [quick_sort](algorithms/sort/quick_sort.py)
283284
- [radix_sort](algorithms/sort/radix_sort.py)
284285
- [selection_sort](algorithms/sort/selection_sort.py)

algorithms/sort/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from .insertion_sort import *
99
from .merge_sort import *
1010
from .pancake_sort import *
11+
from .pigeonhole_sort import *
1112
from .quick_sort import *
1213
from .selection_sort import *
1314
from .top_sort import *

algorithms/sort/pigeonhole_sort.py

+28
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

+5-1
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,
@@ -67,7 +68,10 @@ def test_merge_sort(self):
6768

6869
def test_pancake_sort(self):
6970
self.assertTrue(is_sorted(pancake_sort([1, 3, 2, 5, 65, 23, 57, 1232])))
70-
71+
72+
def test_pigeonhole_sort(self):
73+
self.assertTrue(is_sorted(pigeonhole_sort([1, 5, 65, 23, 57, 1232])))
74+
7175
def test_quick_sort(self):
7276
self.assertTrue(is_sorted(quick_sort([1, 3, 2, 5, 65, 23, 57, 1232])))
7377

0 commit comments

Comments
 (0)