Skip to content

Commit b321b15

Browse files
committed
[cpp][12_sorts] inplace_merge_sort, done.
1 parent 6a2f303 commit b321b15

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

c-cpp/12_sorts/merge_sort.hpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,5 +47,16 @@ void merge_sort(FrwdIt first, FrwdIt last, BinaryPred comp = BinaryPred()) {
4747
std::copy(tmp.begin(), tmp.end(), first);
4848
}
4949

50+
template <typename BidirIt,
51+
typename BinaryPred = std::less<typename std::iterator_traits<BidirIt>::value_type>>
52+
void inplace_merge_sort(BidirIt first, BidirIt last, BinaryPred comp = BinaryPred()) {
53+
const auto len = std::distance(first, last);
54+
if (len <= 1) { return; }
55+
auto cut = first + len / 2;
56+
merge_sort(first, cut, comp);
57+
merge_sort(cut, last, comp);
58+
std::inplace_merge(first, cut, last, comp);
59+
}
60+
5061
#endif // SORTS_MERGE_SORT_HPP_
5162

c-cpp/12_sorts/merge_sort_test.cc

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,18 @@
77
#include "merge_sort.hpp"
88

99
int main() {
10-
std::vector<int> test_data{0, -1, 3, 190, -500};
11-
merge_sort(test_data.begin(), test_data.end());
12-
for (auto i : test_data) {
10+
const std::vector<int> test_data{0, -1, 3, 190, -500};
11+
12+
std::vector<int> a{test_data};
13+
merge_sort(a.begin(), a.end());
14+
for (auto i : a) {
15+
std::cout << i << ' ';
16+
}
17+
std::cout << std::endl;
18+
19+
std::vector<int> b{test_data};
20+
inplace_merge_sort(b.begin(), b.end());
21+
for (auto i : b) {
1322
std::cout << i << ' ';
1423
}
1524
std::cout << std::endl;

0 commit comments

Comments
 (0)