forked from TheAlgorithms/C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpigeonhole_sort.c
73 lines (63 loc) · 1.35 KB
/
pigeonhole_sort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <stdio.h>
#include <stdlib.h>
void pigeonholeSort(int arr[], int size)
{
int i, j, min = arr[0], max = arr[0], range;
// 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;
// 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]++;
}
// Copy the numbers back to the original array
j = 0;
for (i = 0; i < range; i++)
{
while (holes[i] > 0)
{
arr[j] = i + min;
holes[i]--;
j++;
}
}
free(holes);
}
int main()
{
int i, n;
printf("Enter the size of the array: ");
scanf("%d", &n);
int *arr = (int *)malloc(sizeof(int) * n);
for (i = 0; i < n; i++)
{
printf("Number #%d: ", i + 1);
scanf("%d", &arr[i]);
}
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");
free(arr);
return 0;
}