-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCounting_sort.cpp
108 lines (99 loc) · 2.54 KB
/
Counting_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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// Copyright (c) 2013 Elements of Programming Interviews. All rights reserved.
#include <algorithm>
#include <cassert>
#include <functional>
#include <iostream>
#include <random>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using std::cout;
using std::default_random_engine;
using std::endl;
using std::hash;
using std::max;
using std::random_device;
using std::swap;
using std::string;
using std::uniform_int_distribution;
using std::unordered_map;
using std::unordered_set;
using std::vector;
// @include
struct Person {
int key;
string name;
};
void counting_sort(vector<Person>* people) {
unordered_map<int, int> key_to_count;
for (const Person& p : *people) {
++key_to_count[p.key];
}
unordered_map<int, int> key_to_offset;
int offset = 0;
for (const auto& p : key_to_count) {
key_to_offset[p.first] = offset;
offset += p.second;
}
while (key_to_offset.size()) {
auto from = key_to_offset.begin();
auto to = key_to_offset.find((*people)[from->second].key);
swap((*people)[from->second], (*people)[to->second]);
// Use key_to_count to see when we are finished with a particular key.
if (--key_to_count[to->first]) {
++to->second;
} else {
key_to_offset.erase(to);
}
}
}
// @exclude
string rand_string(int len) {
string ret;
default_random_engine gen((random_device())());
uniform_int_distribution<int> char_dis(0, 25);
while (len--) {
ret += 'a' + char_dis(gen);
}
return ret;
}
int main(int argc, char* argv[]) {
default_random_engine gen((random_device())());
for (int times = 0; times < 1000; ++times) {
int size;
if (argc == 2 || argc == 3) {
size = atoi(argv[1]);
} else {
uniform_int_distribution<int> dis(1, 10000);
size = dis(gen);
}
int k;
if (argc == 3) {
k = atoi(argv[2]);
} else {
uniform_int_distribution<int> dis(1, size);
k = dis(gen);
}
vector<Person> people;
uniform_int_distribution<int> k_dis(0, k - 1);
uniform_int_distribution<int> len_dis(1, 10);
for (int i = 0; i < size; ++i) {
people.emplace_back(Person{k_dis(gen), rand_string(len_dis(gen))});
}
unordered_set<int> key_set;
for (const Person& p : people) {
key_set.emplace(p.key);
}
counting_sort(&people);
// Check the correctness of sorting.
int diff_count = 1;
for (int i = 1; i < people.size(); ++i) {
if (people[i].key != people[i - 1].key) {
++diff_count;
}
}
assert(diff_count == key_set.size());
}
return 0;
}