AlgoPlus v0.1.0
Loading...
Searching...
No Matches
counting_sort.h
1#ifndef ALGOPLUS_COUNTING_SORT_H
2#define ALGOPLUS_COUNTING_SORT_H
3
4#ifdef __cplusplus
5#include <algorithm>
6#include <cstdint>
7#include <vector>
8#endif
9
15template <typename T> void counting_sort(std::vector<T>& arr) {
16 T maxElement = std::max(0, *max_element(arr.begin(), arr.end()));
17 std::vector<T> count(maxElement + 1, 0);
18 std::vector<T> output(arr.size());
19
20 // Store count of each element
21 for (int64_t i = 0; i < arr.size(); i++) {
22 count[arr[i]]++;
23 }
24
25 // Change count[i] so that count[i] now contains actual position of this
26 // element in output array
27 for (int64_t i = 1; i <= maxElement; i++) {
28 count[i] += count[i - 1];
29 }
30
31 // Build the output array
32 for (int64_t i = arr.size() - 1; i >= 0; i--) {
33 output[count[arr[i]] - 1] = arr[i];
34 count[arr[i]]--;
35 }
36
37 arr = output;
38}
39
40#endif // ALGOPLUS_COUNTING_SORT_H