2019-10-05 05:14:13 +00:00
|
|
|
"""
|
2024-03-13 06:52:41 +00:00
|
|
|
This is an implementation of Pigeon Hole Sort.
|
|
|
|
For doctests run following command:
|
2020-05-22 06:10:11 +00:00
|
|
|
|
2024-03-13 06:52:41 +00:00
|
|
|
python3 -m doctest -v pigeon_sort.py
|
|
|
|
or
|
|
|
|
python -m doctest -v pigeon_sort.py
|
2020-05-22 06:10:11 +00:00
|
|
|
|
2024-03-13 06:52:41 +00:00
|
|
|
For manual testing run:
|
|
|
|
python pigeon_sort.py
|
2019-10-05 05:14:13 +00:00
|
|
|
"""
|
2024-03-13 06:52:41 +00:00
|
|
|
|
2021-09-07 11:37:03 +00:00
|
|
|
from __future__ import annotations
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
|
2021-09-07 11:37:03 +00:00
|
|
|
def pigeon_sort(array: list[int]) -> list[int]:
|
2019-10-03 08:19:11 +00:00
|
|
|
"""
|
|
|
|
Implementation of pigeon hole sort algorithm
|
|
|
|
:param array: Collection of comparable items
|
|
|
|
:return: Collection sorted in ascending order
|
|
|
|
>>> pigeon_sort([0, 5, 3, 2, 2])
|
|
|
|
[0, 2, 2, 3, 5]
|
|
|
|
>>> pigeon_sort([])
|
|
|
|
[]
|
|
|
|
>>> pigeon_sort([-2, -5, -45])
|
|
|
|
[-45, -5, -2]
|
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
if len(array) == 0:
|
2019-10-03 08:19:11 +00:00
|
|
|
return array
|
|
|
|
|
2020-11-30 14:59:23 +00:00
|
|
|
_min, _max = min(array), max(array)
|
2019-05-24 17:16:39 +00:00
|
|
|
|
|
|
|
# Compute the variables
|
2020-11-30 14:59:23 +00:00
|
|
|
holes_range = _max - _min + 1
|
|
|
|
holes, holes_repeat = [0] * holes_range, [0] * holes_range
|
2019-05-24 17:16:39 +00:00
|
|
|
|
|
|
|
# Make the sorting.
|
2020-11-30 14:59:23 +00:00
|
|
|
for i in array:
|
|
|
|
index = i - _min
|
|
|
|
holes[index] = i
|
|
|
|
holes_repeat[index] += 1
|
2019-05-24 17:16:39 +00:00
|
|
|
|
|
|
|
# Makes the array back by replacing the numbers.
|
|
|
|
index = 0
|
|
|
|
for i in range(holes_range):
|
2019-10-05 05:14:13 +00:00
|
|
|
while holes_repeat[i] > 0:
|
2019-05-24 17:16:39 +00:00
|
|
|
array[index] = holes[i]
|
|
|
|
index += 1
|
|
|
|
holes_repeat[i] -= 1
|
|
|
|
|
|
|
|
# Returns the sorted array.
|
|
|
|
return array
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2020-11-30 14:59:23 +00:00
|
|
|
import doctest
|
2020-11-30 15:33:29 +00:00
|
|
|
|
2020-11-30 14:59:23 +00:00
|
|
|
doctest.testmod()
|
2019-10-05 05:14:13 +00:00
|
|
|
user_input = input("Enter numbers separated by comma:\n")
|
|
|
|
unsorted = [int(x) for x in user_input.split(",")]
|
2019-10-03 08:19:11 +00:00
|
|
|
print(pigeon_sort(unsorted))
|