diff --git a/README.md b/README.md index bb6c4c09c..e26c02dde 100644 --- a/README.md +++ b/README.md @@ -279,6 +279,7 @@ If you want to uninstall algorithms, it is as simple as: - [meeting_rooms](algorithms/sort/meeting_rooms.py) - [merge_sort](algorithms/sort/merge_sort.py) - [pancake_sort](algorithms/sort/pancake_sort.py) + - [pigeonhole_sort](algorithms/sort/pigeonhole_sort.py) - [quick_sort](algorithms/sort/quick_sort.py) - [radix_sort](algorithms/sort/radix_sort.py) - [selection_sort](algorithms/sort/selection_sort.py) diff --git a/algorithms/sort/__init__.py b/algorithms/sort/__init__.py index 5a870feff..b948dba48 100644 --- a/algorithms/sort/__init__.py +++ b/algorithms/sort/__init__.py @@ -8,6 +8,7 @@ from .insertion_sort import * from .merge_sort import * from .pancake_sort import * +from .pigeonhole_sort import * from .quick_sort import * from .selection_sort import * from .top_sort import * diff --git a/algorithms/sort/pigeonhole_sort.py b/algorithms/sort/pigeonhole_sort.py new file mode 100644 index 000000000..0569aa994 --- /dev/null +++ b/algorithms/sort/pigeonhole_sort.py @@ -0,0 +1,28 @@ +""" + +https://en.wikipedia.org/wiki/Pigeonhole_sort + +Time complexity: O(n + Range) where n = number of elements and Range = possible values in the array + +Suitable for lists where the number of elements and key values are mostly the same. + +""" + + +def pigeonhole_sort(arr): + Max = max(arr) + Min = min(arr) + size = Max - Min + 1 + + holes = [0]*size + + for i in arr: + holes[i-Min] += 1 + + i = 0 + for count in range(size): + while holes[count] > 0: + holes[count] -= 1 + arr[i] = count + Min + i += 1 + return arr diff --git a/tests/test_sort.py b/tests/test_sort.py index c24e20da8..e3fb498b7 100644 --- a/tests/test_sort.py +++ b/tests/test_sort.py @@ -9,6 +9,7 @@ insertion_sort, merge_sort, pancake_sort, + pigeonhole_sort, quick_sort, selection_sort, bucket_sort, @@ -67,7 +68,10 @@ def test_merge_sort(self): def test_pancake_sort(self): self.assertTrue(is_sorted(pancake_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) - + + def test_pigeonhole_sort(self): + self.assertTrue(is_sorted(pigeonhole_sort([1, 5, 65, 23, 57, 1232]))) + def test_quick_sort(self): self.assertTrue(is_sorted(quick_sort([1, 3, 2, 5, 65, 23, 57, 1232])))