Pigeonhole sort is a non-comparison sorting algorithm that performs sorting in linear time. This algorithm is utilized to sort the integer values where the array length and the range of elements are close. It creates a pigeonhole for each possible data value and places the data items in their corresponding pigeonhole. Lastly, it collects the data items in ascending order to sort the data.
A practical example of pigeonhole sort could be the cabinets in the post offices where every slot represents ZIP codes or other distinguished keys from where the postman can collect the packages. Whenever a new package arrives, it is placed in its proper slot manually.
The algorithm works in the following steps:
Play the following slides to visualize the working of the pigeonhole sort:
Let’s see the pseudocode of this algorithm before implementing it in any programming language.
min_value := find_min(array)max_value := find_max(array)range := max_value - min_value + 1pigenholes := array[range]for i from 0 to n:push array[i] into pigenholes[array[i] - min]arr_index = 0for i from 0 to range:while(pigenhole[i] is not empty):place pigeonhole elements in array[arr_index]arr_index := arr_index + 1
Let’s implement the code of pigeonhole sort using Python in the following playground:
def pigeonhole_sort(array):min_value = min(array)max_value = max(array)range_value = max_value - min_value + 1pigeonholes = [[] for _ in range(range_value)]for i in range(len(array)):pigeonholes[array[i] - min_value].append(array[i])arr_index = 0for i in range(range_value):while pigeonholes[i]:array[arr_index] = pigeonholes[i].pop(0)arr_index += 1returnarray = [18, 13, 15, 11, 19, 12, 14, 13]print("Unsorted array:", array)pigeonhole_sort(array)print("Sorted array:", array)
Let’s discuss the code below:
arr_index
to store the index and loop through pigeonhole elements. We use a while
loop to push the values of each pigeonhole to the original array in order. Lastly, we increment the arr_index
after the transfer of each element.pigeonhole_sort()
function and print the array after sorting.The time and space complexity of the pigeonhole sort algorithm is , where is the length of the array, and is the range of the array elements.
Let’s discuss some benefits and limitations of the Pigeonhole sort.
Pigeonhole sort is a non-comparison-based algorithm, which means it doesn’t compare elements for sorting. This is beneficial where comparisons are costly.
It is a stable algorithm, which means it maintains the order of equal elements.
It is a linear time algorithm that performs sorting quickly. It is faster than comparison-based sorting algorithms, i.e., merge sort or quick sort.
Free Resources