forked from VladimirBalun/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSorting.cpp
More file actions
62 lines (51 loc) · 1.56 KB
/
Copy pathMergeSorting.cpp
File metadata and controls
62 lines (51 loc) · 1.56 KB
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
#include <vector>
#include <iostream>
template<typename Collection, typename Comparator, typename = typename Collection::iterator>
void merge_sorting(Collection& collection, std::size_t begin, std::size_t end, Comparator comparator) noexcept
{
if (end - begin < 2)
return;
const std::size_t middle = (begin + end) / 2;
merge_sorting(collection, begin, middle, comparator);
merge_sorting(collection, middle, end, comparator);
Collection buffer{};
buffer.reserve(end - begin);
std::size_t left = begin;
std::size_t right = middle;
while ( (left < middle) && (right < end) )
{
if (comparator(collection.at(left), collection.at(right)))
{
buffer.push_back(collection.at(left));
left++;
}
else
{
buffer.push_back(collection.at(right));
right++;
}
}
while (left < middle)
{
buffer.push_back(collection.at(left));
left++;
}
while (right < end)
{
buffer.push_back(collection.at(right));
right++;
}
std::copy(buffer.begin(), buffer.end(), collection.begin() + begin);
}
int main()
{
std::vector<int> vector = { 7, 9, 1, 5, 8, 1, 8, 3, 7, 3 };
std::cout << "Not sorted array: ";
for (const auto& value : vector)
std::cout << value << " ";
merge_sorting(vector, 0, vector.size(), [](int a, int b) -> bool { return a < b; });
std::cout << "\nSorted array: ";
for (const auto& value : vector)
std::cout << value << " ";
return EXIT_SUCCESS;
}