-
Notifications
You must be signed in to change notification settings - Fork 368
/
Pigeonhole sort.c
53 lines (43 loc) · 1.04 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
#include <stdio.h>
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;
int* pigeonholes = (int*)malloc(range * sizeof(int));
memset(pigeonholes, 0, range * sizeof(int));
for (int i = 0; i < n; i++) {
pigeonholes[arr[i] - min]++;
}
int index = 0;
for (int i = 0; i < range; i++) {
while (pigeonholes[i] > 0) {
arr[index++] = i + min;
pigeonholes[i]--;
}
}
free(pigeonholes);
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
pigeonholeSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}