Pigeonhole sorting is a sorting algorithm that is suitable for sorting lists of elements where the number of elements and the number of possible key values are approximately the same.
It requires O(n + Range) time where n is number of elements in input array and ‘Range’ is number of possible values in array.
Working of Algorithm :
- Find minimum and maximum values in array. Let the minimum and maximum values be ‘min’ and ‘max’ respectively. Also find range as ‘max-min+1’.
- Set up an array of initially empty “pigeonholes” the same size as of the range.
- Visit each element of the array and then put each element in its pigeonhole. An element arr[i] is put in hole at index arr[i] – min.
- Start the loop all over the pigeonhole array in order and put the elements from non- empty holes back into the original array.
Comparison with Counting Sort :
It is similar to counting sort, but differs in that it “moves items twice: once to the bucket array and again to the final destination “.
Sorted order is : 2 3 4 6 7 8 8
Pigeonhole sort has limited use as requirements are rarely met. For arrays where range is much larger than n, bucket sort is a generalization that is more efficient in space and time.
This article is contributed Ayush Govil. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- C++ Program for Pigeonhole Sort
- Java Program for Pigeonhole Sort
- Mathematics | The Pigeonhole Principle
- Comparison among Bubble Sort, Selection Sort and Insertion Sort
- Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
- Add elements in start to sort the array | Variation of Stalin Sort
- Program to sort an array of strings using Selection Sort
- Bucket Sort To Sort an Array with Negative Numbers
- Insertion sort to sort even and odd positioned elements in different orders
- Java Program for Odd-Even Sort / Brick Sort
- Sort an Array which contain 1 to N values in O(N) using Cycle Sort
- Odd Even Transposition Sort / Brick Sort using pthreads
- Serial Sort v/s Parallel Sort in Java
- C/C++ Program for Odd-Even Sort / Brick Sort
- Quick Sort vs Merge Sort
- sort() vs. partial_sort() vs. nth_element() + sort() in C++ STL
- Merge Sort vs. Insertion Sort
- Odd-Even Sort / Brick Sort
- Sort all even numbers in ascending order and then sort all odd numbers in descending order
- std::sort() in C++ STL