-
Notifications
You must be signed in to change notification settings - Fork 0
/
bucketsort.cpp
79 lines (66 loc) · 1.69 KB
/
bucketsort.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
74
75
76
77
78
79
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <random>
using namespace std;
bool isAnagram(string a, string b) {
std::vector<int> res(26);
for(auto& character : a) {
int index = character - 'a';
res[index]++;
}
for(auto& character : b) {
int index = character - 'a';
res[index]--;
}
for(auto& value : res) {
if(value != 0) return false;
}
return true;
}
struct Bucket {
Bucket(string& a) {
insert(a);
}
bool doesThisBelong(string& a) {
if(values.empty()) return true;
return isAnagram(*values.begin(), a);
}
void insert(string& a) {
values.push_back(a);
}
void output() {
for(auto& value : values) {
cout << value << ' ';
}
}
private:
vector<string> values;
};
void sort(vector<string>& strings, vector<Bucket>& buckets) {
for(auto value : strings) {
bool inserted = false;
for(auto& bucket : buckets) {
if(bucket.doesThisBelong(value)) {
bucket.insert(value);
inserted = true;
}
}
if(!inserted) {
buckets.push_back(Bucket(value));
}
}
}
int main()
{
vector<Bucket> res;
vector<string> v = {"oliverqueen"s, "noliverquee"s, "barryallen"s, "allenbarry"s, "cat"s, "tac"s, "butthole", "holebutt"s, "fog"s, "gof"s, "bat"s, "tab"s };
sort(v, res);
for(auto& bucket : res) {
bucket.output();
cout << "\n\n";
}
}