-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path47_Count_sort.cpp
73 lines (65 loc) · 1.41 KB
/
47_Count_sort.cpp
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 <bits/stdc++.h>
using namespace std;
void printArray(int *arr, int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
}
int maximum(int *arr, int n)
{
int max = INT_MIN;
for (int i = 0; i < n; i++)
{
if (max < arr[i])
{
max = arr[i];
}
}
return max;
}
void countSort(int *arr, int n)
{
int i, j;
// find the maximum element in A
int max = maximum(arr, n);
// create the count array
int *count = (int *)malloc((max + 1) * sizeof(int));
// initialize the array elements to 0
for (i = 0; i < max + 1; i++)
{
count[i] = 0;
}
// increment the corresponding index in the count array
for (i = 0; i < n; i++)
{
count[arr[i]] = count[arr[i]] + 1;
}
i = 0; // counter for count array
j = 0; // counter for given array arr
while (i <= max)
{
if (count[i] > 0)
{
arr[j] = i;
count[i] = count[i] - 1;
j++;
}
else
{
i++;
}
}
}
int main()
{
int arr[] = {12, 74, 89, 3, 14, 25, 47, 99};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "The given array is: ";
printArray(arr, size);
countSort(arr, size);
cout << "\nThe sorted array is: ";
printArray(arr, size);
return 0;
}