Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sorting: Pigeonhole Sort in Cpp #281

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions Sorting/Pigeonhole Sort/PigeonholeSort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <bits/stdc++.h>
using namespace std;

void pigeonholeSort(int arr[], int n)
{
int min = arr[0], max = arr[0];
for (int i = 1; i < n; i++)
{
if (arr[i] < min)
min = arr[i];
if (arr[i] > max)
max = arr[i];
}
int range = max - min + 1; // Find range

vector<int> holes[range];

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

int index = 0; // index in sorted array
for (int i = 0; i < range; i++)
{
vector<int>::iterator it;
for (it = holes[i].begin(); it != holes[i].end(); ++it)
arr[index++] = *it;
}
}

int main()
{
int arr[] = {8, 3, 2, 7, 4, 6, 8};
int n = sizeof(arr)/sizeof(arr[0]);

pigeonholeSort(arr, n);

printf("Sorted order is : ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);

return 0;
}