diff --git a/Data Structures and Algorithms/Sorting Algorithms/Pigeonhole_Sort.py b/Data Structures and Algorithms/Sorting Algorithms/Pigeonhole_Sort.py new file mode 100644 index 00000000..11a60934 --- /dev/null +++ b/Data Structures and Algorithms/Sorting Algorithms/Pigeonhole_Sort.py @@ -0,0 +1,33 @@ +# Python program to implement Pigeonhole Sort + +def pigeonhole_sort(a): + # size of range of values in the list + # (ie, number of pigeonholes we need) + my_min = min(a) + my_max = max(a) + size = my_max - my_min + 1 + + # our list of pigeonholes + holes = [0] * size + + # Populate the pigeonholes. + for x in a: + assert type(x) is int, "integers only" + holes[x - my_min] += 1 + + # Put the elements back into the array in order. + i = 0 + for count in range(size): + while holes[count] > 0: + holes[count] -= 1 + a[i] = count + my_min + i += 1 + + +a = [8, 1, 2, 7, 4, 5, 8] +print("Sorted order is : ", end = ' ') + +pigeonhole_sort(a) + +for i in range(0, len(a)): + print(a[i], end = ' ') diff --git a/Data Structures and Algorithms/Sorting Algorithms/README.md b/Data Structures and Algorithms/Sorting Algorithms/README.md index a951a505..7ddfda4b 100644 --- a/Data Structures and Algorithms/Sorting Algorithms/README.md +++ b/Data Structures and Algorithms/Sorting Algorithms/README.md @@ -23,3 +23,27 @@ print("Original array:", arr) writes = cycle_sort(arr) print("Sorted array:", arr) print("Number of writes performed:", writes) +``` +# Pigeonhole Sort Algorithm + +## Overview +Pigeonhole Sort is a sorting algorithm that works well for sorting lists where the range of values (i.e., the difference between the maximum and minimum values) is not significantly larger than the number of elements in the list. It is a non-comparison-based sorting algorithm. + +The algorithm works by placing each element into its corresponding "pigeonhole" (a slot or bucket) and then iterating through the pigeonholes in order to reconstruct the sorted list. + +## Complexity +- **Time Complexity**: + - The time complexity of Pigeonhole Sort is O(n + range), where n is the number of elements in the list and range is the difference between the maximum and minimum values. + + - This makes it efficient for lists with a small range of values. +- **Space Complexity**: The space complexity is O(range), as it requires additional space for the holes list. +- **Limitations**: Pigeonhole Sort is not suitable for lists with a large range of values, as it would require a lot of memory for the holes list. + +## Usage Example +```python +from PigeonHole_Sort import pigeonhole_sort + +arr = [4, 5, 3, 2, 1] +print("Original array:", arr) +writes = pigeonhole_sort(arr) +print("Sorted array:", arr)