Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to merge elements of two sorted not equal vectors by maintaining the sorted order in C++

2 Answers

0 votes
#include <vector>
#include <iostream>
 
void print_vector(std::vector<int> const &v) {
    for (auto const &n: v) {
        std::cout << n << " ";
    }
}
 
void merge_sorted_not_equal_arrays(std::vector<int> &vec1, std::vector<int> &vec2) {
    int size1 = vec1.size();
    int size2 = vec2.size();
 
    for (int i = 0; i < size1; i++) {
        if (vec1[i] > vec2[0]) {
            // swap 
            int tmp = vec1[i];
            vec1[i] = vec2[0];
            vec2[0] = tmp;
 
            int element0 = vec2[0];
 
            // Move vec2[0] to the correct position to maintain the sorted order
            int k;
            for (k = 1; k < size2 && vec2[k] < element0; k++) {
                vec2[k - 1] = vec2[k];
            }
 
            vec2[k - 1] = element0;
        }
    }
}
 
int main()
{
    std::vector<int> vec1 = {1, 4, 6, 8, 10};
    std::vector<int> vec2 = {2, 3, 5, 9};
 
    merge_sorted_not_equal_arrays(vec1, vec2);
 
    print_vector(vec1);
    std::cout << "\n";
    print_vector(vec2);
}
 
 
 
 
/*
run:
  
1 2 3 4 5 
6 8 9 10 
  
*/

 



answered Sep 16, 2023 by avibootz
edited Sep 16, 2023 by avibootz
0 votes
#include <vector>
#include <iostream>
 
void print_vector(std::vector<int> const &v) {
    for (auto const &n: v) {
        std::cout << n << " ";
    }
}
 
void merge_sorted_not_equal_arrays(std::vector<int> &vec1, std::vector<int> &vec2) {
    int size1 = vec1.size();
    int size2 = vec2.size();
 
    for (int i = size2 - 1; i >= 0; i--) {
        int j, last1 = vec1[size1 - 1];
        for (j = size1 - 2; j >= 0 && vec1[j] > vec2[i]; j--) {
            vec1[j + 1] = vec1[j];
        }
        if (last1 > vec2[i]) {
            vec1[j + 1] = vec2[i];
            vec2[i] = last1;
        }
    }
}
 
int main()
{
    std::vector<int> vec1 = {1, 4, 6, 8, 10};
    std::vector<int> vec2 = {2, 3, 5, 9};
 
    merge_sorted_not_equal_arrays(vec1, vec2);
 
    print_vector(vec1);
    std::cout << "\n";
    print_vector(vec2);
}
 
 
 
 
/*
run:
  
1 2 3 4 5 
6 8 9 10 
  
*/

 



answered Sep 16, 2023 by avibootz
edited Sep 16, 2023 by avibootz
...