TheAlgorithms-Python
61 строка · 1.4 Кб
1"""
2This is an implementation of Pigeon Hole Sort.
3For doctests run following command:
4
5python3 -m doctest -v pigeon_sort.py
6or
7python -m doctest -v pigeon_sort.py
8
9For manual testing run:
10python pigeon_sort.py
11"""
12
13from __future__ import annotations14
15
16def pigeon_sort(array: list[int]) -> list[int]:17"""18Implementation of pigeon hole sort algorithm
19:param array: Collection of comparable items
20:return: Collection sorted in ascending order
21>>> pigeon_sort([0, 5, 3, 2, 2])
22[0, 2, 2, 3, 5]
23>>> pigeon_sort([])
24[]
25>>> pigeon_sort([-2, -5, -45])
26[-45, -5, -2]
27"""
28if len(array) == 0:29return array30
31_min, _max = min(array), max(array)32
33# Compute the variables34holes_range = _max - _min + 135holes, holes_repeat = [0] * holes_range, [0] * holes_range36
37# Make the sorting.38for i in array:39index = i - _min40holes[index] = i41holes_repeat[index] += 142
43# Makes the array back by replacing the numbers.44index = 045for i in range(holes_range):46while holes_repeat[i] > 0:47array[index] = holes[i]48index += 149holes_repeat[i] -= 150
51# Returns the sorted array.52return array53
54
55if __name__ == "__main__":56import doctest57
58doctest.testmod()59user_input = input("Enter numbers separated by comma:\n")60unsorted = [int(x) for x in user_input.split(",")]61print(pigeon_sort(unsorted))62