Skip to content

Commit 1dc77a8

Browse files
committed
[cpp][12_sorts] inplace_merge_sort, impl inplace_merge manually.
1 parent b321b15 commit 1dc77a8

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

c-cpp/12_sorts/merge_sort.hpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,17 @@ OutputIt merge(InputIt1 first1, InputIt1 last1,
3131
}
3232
return std::copy(first2, last2, d_first);
3333
}
34+
35+
template <typename FrwdIt,
36+
typename BinaryPred = std::less<typename std::iterator_traits<FrwdIt>::value_type>>
37+
void inplace_merge(FrwdIt first, FrwdIt middle, FrwdIt last, BinaryPred comp = BinaryPred()) {
38+
// with sufficient memory space
39+
const auto len = std::distance(first, last);
40+
std::vector<typename std::iterator_traits<FrwdIt>::value_type> tmp;
41+
tmp.reserve(len);
42+
detail::merge(first, middle, middle, last, std::back_inserter(tmp), comp);
43+
std::copy(tmp.begin(), tmp.end(), first);
44+
}
3445
} // namespace detail
3546

3647
template <typename FrwdIt,

0 commit comments

Comments
 (0)