AlgoPlus v0.1.0
Loading...
Searching...
No Matches
bucket_sort.h
1#ifndef BUCKET_SORT_H
2#define BUCKET_SORT_H
3
4#ifdef __cplusplus
5#include <algorithm>
6#include <cstdint>
7#include <iostream>
8#include <vector>
9#endif
10
15template <typename T> void bucket_sort(std::vector<T>& arr) {
16 if (std::is_same_v<T, int> || std::is_same_v<T, int64_t>) {
17 std::sort(arr.begin(), arr.end());
18 return;
19 }
20 std::vector<float> buckets[arr.size()];
21 for (int64_t i = 0; i < arr.size(); i++) {
22 int64_t index = arr.size() * arr[i];
23 buckets[index].push_back(arr[i]);
24 }
25
26 for (int64_t i = 0; i < arr.size(); i++) {
27 std::sort(buckets[i].begin(), buckets[i].end());
28 }
29
30 int64_t index = 0;
31 for (int64_t i = 0; i < arr.size(); i++) {
32 for (int64_t j = 0; j < buckets[i].size(); j++) {
33 arr[index++] = buckets[i][j];
34 }
35 }
36}
37
38#endif