You need to merge two vectors using two priprity queues to form a zig-zag vector
ID: 3817466 • Letter: Y
Question
You need to merge two vectors using two priprity queues to form a zig-zag vector. The zigzag vector should have the sorted vectors interspersed with each other.
Example Output:
#include <iostream>
#include <queue>
#include <string>
using namespace std;
vector<int> zigZag(vector<int> v1, vector<int> v2){
//Write code here
}
int main(){
vector<int> v1, v2;
v1 = {50,40,20,30,10};
v2 = {1,2,3,4,5};
vector<int>answer = zigZag(v1,v2);
cout << "The zig zag vector is " <<endl;
for (int i =0; i < (int)answer.size(); i ++){
cout << answer[i]<<endl;
}
return 0;
}
Explanation / Answer
//program
#include <iostream>
#include <queue>
#include <string>
using namespace std;
vector<int> zigZag(vector<int> v1, vector<int> v2)
{
//Write code here
priority_queue<int> pq1;
priority_queue<int> pq2;
vector<int> merge;
//push v1 onto pq1
for (int i = 0; i < v1.size(); i++)
pq1.push(v1[i]);
//push v2 onto pq2
for (int i = 0; i < v2.size(); i++)
pq2.push(v2[i]);
int j = 0,num;
while (j < v1.size() )
{
merge.push_back(pq1.top());
pq1.pop();
merge.push_back(pq2.top());
pq2.pop();
j++;
}
return merge;
}
int main(){
vector<int> v1, v2;
v1 = { 50, 40, 20, 30, 10 };
v2 = { 1, 2, 3, 4, 5 };
vector<int>answer = zigZag(v1, v2);
cout << "The zig zag vector is " << endl;
for (int i = 0; i < (int)answer.size(); i++){
cout << answer[i] << endl;
}
return 0;
}
-----------------------------------------------------------
//output
pq1: top: 50
pq2: top: 5
pq1: top: 40
pq2: top: 4
pq1: top: 30
pq2: top: 3
pq1: top: 20
pq2: top: 2
pq1: top: 10
pq2: top: 1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.