-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcounting_sort1.cpp
More file actions
50 lines (40 loc) 路 930 Bytes
/
Copy pathcounting_sort1.cpp
File metadata and controls
50 lines (40 loc) 路 930 Bytes
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
#include <iostream>
using namespace std;
void printArray(int arr[], int size)
{
for (int i = 0; i < size; ++i)
{
cout << arr[i] << " ";
}
cout << endl;
}
int *countSort(int arr[], int size, int k)
{
int count[k + 1] = {0};
int *result = (int *)malloc(size * sizeof(int));
for (int i = 0; i < size; ++i)
{
count[arr[i]]++;
}
for (int i = 1; i <= k; ++i)
{
count[i] = count[i] + count[i - 1];
}
for (int i = size - 1; i >= 0; --i)
{
count[arr[i]]--;
result[count[arr[i]]] = arr[i];
}
return result;
}
int main()
{
int arr[] = {0, 1, 2, 5, 4, 3, 4, 2, 5, 1, 2, 2, 2, 6, 1, 1, 3, 5, 1, 5, 0, 0, 6};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Unsorted array: ";
printArray(arr, size);
int *res = countSort(arr, size, 6);
cout << "Sorted array: ";
printArray(res, size);
return 0;
}