# Pigeonhole Sort

This is an example of the non-comparison sorting technique. It is used where the number of items and the range of possible key values is approximately the same.

To perform this sort, we need to make some holes. The number of holes needed is decided by the range of numbers. In each hole, items are inserted. Finally deleted from the hole and stored into an array for sorted order.

## The complexity of Pigeon-Hole Sort Technique

• Time Complexity: O(n+2^k)
• Space Complexity: O(2^k)

## Input and Output

Input:
The unsorted list: 802 630 20 745 52 300 612 932 78 187
Output:
Data before Sorting: 802 630 20 745 52 300 612 932 78 187
Data after Sorting: 20 52 78 187 300 612 630 745 802 932

## Algorithm

pigeonHoleSort(array, size)

Input − An array of data, and the total number in the array

Output − The sorted Array

Begin
find max and min from the array list
holeRange := max – min +1
define holeRange number of Lists

for i := 0 to n-1 do
hole[array[i]-min].append(array[i])
done

count := 0
for j := 0 to holeRange-1 do
while hole[j] is not empty do
array[count] := get first node of hole[j] and delete it
count := count +1
done
done
End

## Example

#include<iostream>
#include<list>
#include<cmath>
using namespace std;

void getMaxMin(int *arr, int n, int &maximum, int &minimum) {
maximum = minimum = arr[0]; //initially max and min ar arr[0]

for(int i = 1; i<n; i++) {
if(arr[i] > maximum)
maximum = arr[i]; //get maximum data
if(arr[i] < minimum)
minimum = arr[i]; //get minimum data
}
}

void pegionHoleSort(int *arr, int n) {
int max, min;
getMaxMin(arr, n, max, min);
int holeRange = max - min +1;
list<int> hole[holeRange]; //create an array of holes

for(int i = 0; i<n; i++) {
hole[arr[i]-min].push_back(arr[i]);
}

int count = 0;
for(int j = 0; j<holeRange; j++) {
//delete from linked lists and store to array
while(!hole[j].empty()) {
arr[count] = *(hole[j].begin());
hole[j].erase(hole[j].begin());
count++;
}
}
}

void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}

int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;

for(int i = 0; i<n; i++) {
cin >> arr[i];
}

cout << "Data before Sorting: ";
display(arr, n);
pegionHoleSort(arr, n);
cout << "Data after Sorting: ";
display(arr, n);
}

## Output

Enter the number of elements: 10
Enter elements:
802 630 20 745 52 300 612 932 78 187
Data before Sorting: 802 630 20 745 52 300 612 932 78 187
Data after Sorting: 20 52 78 187 300 612 630 745 802 932

Updated on: 15-Jun-2020

728 Views