Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- template <typename It, typename Cmp=std::less<typename std::iterator_traits<It>::value_type>>
- void InplaceMerge(It first_beg, It first_end, It second_beg, It second_end, Cmp cmp=Cmp()) {
- size_t first_part_size = std::distance(first_beg, first_end);
- size_t second_part_size = std::distance(second_beg, second_end);
- if (!first_part_size || !second_part_size) {
- return;
- }
- if (first_part_size == 1 && second_part_size == 1) {
- if (*first_beg > *second_beg) {
- std::swap(*first_beg, *second_beg);
- }
- return;
- }
- It B1_beg = first_beg;
- It B1_end;
- It B2_beg;
- It B3_beg = second_beg;
- It B3_end;
- It B4_beg;
- It B4_end = second_end;
- if (first_part_size >= second_part_size) {
- B1_end = B1_beg + first_part_size / 2;
- B2_beg = B1_end;
- auto sep = std::lower_bound(second_beg, second_end, *B2_beg);
- B3_end = sep;
- B4_beg = sep;
- } else {
- B3_end = B3_beg + second_part_size / 2;
- B4_beg = B3_end;
- auto sep = std::upper_bound(first_beg, first_end, *B4_beg);
- B1_end = sep;
- B2_beg = sep;
- }
- std::rotate(B2_beg, B3_beg, B3_end);
- auto B3_size = std::distance(B3_beg, B3_end);
- InplaceMerge(B1_beg, B1_end, B2_beg, B2_beg + B3_size);
- InplaceMerge(B2_beg + B3_size, B3_end, B4_beg, B4_end);
- }
- int main() {
- std::vector<int> arr;
- size_t first_part_size = 0;
- std::cin >> first_part_size;
- arr.resize(first_part_size);
- int elem;
- for(auto& i : arr) {
- std::cin >> elem;
- i = elem;
- }
- size_t second_arr_size = 0;
- std::cin >> second_arr_size;
- arr.resize(first_part_size + second_arr_size);
- for(auto it = arr.begin() + first_part_size; it != arr.end(); it = std::next(it)) {
- std::cin >> elem;
- *it = elem;
- }
- InplaceMerge(arr.begin(), arr.begin() + first_part_size, arr.begin() + first_part_size, arr.end());
- for(const auto& val : arr) {
- std::cout << val << ' ';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement