TheAlgorithms-C/sorting/pigeonhole_sort.c

73 lines
1.4 KiB
C
Raw Permalink Normal View History

2020-04-18 14:00:23 +03:00
#include <stdio.h>
#include <stdlib.h>
void pigeonholeSort(int arr[], int size)
2020-04-18 14:00:23 +03:00
{
int i, j, min = arr[0], max = arr[0], range;
2020-04-18 14:00:23 +03:00
// Getting range of the array using max and min
for (i = 1; i < size; i++)
{
if (arr[i] < min)
min = arr[i];
if (arr[i] > max)
max = arr[i];
}
range = max - min + 1;
2020-04-18 14:00:23 +03:00
// Make 'holes' and put array's numbers in holes
int *holes = (int *)malloc(sizeof(int) * range);
for (i = 0; i < range; i++)
{
holes[i] = 0;
}
for (i = 0; i < size; i++)
{
holes[arr[i] - min]++;
}
2020-04-18 14:00:23 +03:00
// Copy the numbers back to the original array
j = 0;
for (i = 0; i < range; i++)
2020-04-18 14:00:23 +03:00
{
while (holes[i] > 0)
{
arr[j] = i + min;
holes[i]--;
j++;
}
2020-04-18 14:00:23 +03:00
}
free(holes);
2020-04-18 14:00:23 +03:00
}
int main()
{
int i, n;
2020-04-18 14:00:23 +03:00
printf("Enter the size of the array: ");
scanf("%d", &n);
int *arr = (int *)malloc(sizeof(int) * n);
2020-04-18 14:00:23 +03:00
for (i = 0; i < n; i++)
{
printf("Number #%d: ", i + 1);
scanf("%d", &arr[i]);
}
2020-04-18 14:00:23 +03:00
printf("You entered: ");
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
pigeonholeSort(arr, n);
printf("\nSorted array: ");
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
2020-04-18 14:00:23 +03:00
free(arr);
return 0;
2020-04-18 14:00:23 +03:00
}