forked from indy256/codelibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort.cpp
52 lines (47 loc) · 1.11 KB
/
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
#include <bits/stdc++.h>
using namespace std;
void merge_sort(vector<int> &a, int low, int high) {
if (high - low < 2)
return;
int mid = (low + high) >> 1;
merge_sort(a, low, mid);
merge_sort(a, mid, high);
vector<int> b;
copy(a.begin() + low, a.begin() + mid, back_inserter(b));
for (int i = low, j = mid, k = 0; k < b.size(); i++) {
if (j == high || b[k] <= a[j]) {
a[i] = b[k++];
} else {
a[i] = a[j++];
}
}
}
void counting_sort(vector<int> &a) {
int max = *max_element(a.begin(), a.end());
vector<int> cnt(max + 1);
for (int x : a) {
++cnt[x];
}
for (int i = 1; i < cnt.size(); i++) {
cnt[i] += cnt[i - 1];
}
int n = a.size();
vector<int> b(n);
for (int i = 0; i < n; i++) {
b[--cnt[a[i]]] = a[i];
}
a = b;
}
// usage example
int main() {
vector<int> a{4, 1, 2, 3};
merge_sort(a, 0, a.size());
for (int x : a)
cout << x << " ";
cout << endl;
a = {4, 1, 2, 3};
counting_sort(a);
for (int x : a)
cout << x << " ";
cout << endl;
}