fork download
  1. using namespace std;
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. // combine two sorted lists A and B into R
  6. // displays comparison every time it is done
  7. void combine(vector<int> A, vector<int> B, vector<int>& R)
  8. {
  9. int ia = 0;
  10. int ib = 0;
  11. int sA = A.size();
  12. int sB = B.size();
  13.  
  14. while ((ia < sA) && (ib < sB)) {
  15. if (A[ia] < B[ib]) {
  16. R.push_back(A[ia]);
  17. ia++;
  18. }
  19. else {
  20. R.push_back(B[ib]);
  21. ib++;
  22. }
  23. }
  24. while(ia < sA)
  25. {
  26. R.push_back(A[ia++]);
  27. }
  28. while(ib < sB)
  29. {
  30. R.push_back(B[ib++]);
  31. }
  32. cout << "comparison" << endl;
  33. // be careful -- R comes in as an empty vector
  34. }
  35.  
  36. int main()
  37. {
  38. vector<int> L1;
  39. vector<int> L2;
  40. vector<int> L3;
  41. int N; // how many elements in each of L1 and L2
  42. int e; // for each element
  43.  
  44. cout << "How many elements in each list?" << endl;
  45. cin >> N;
  46.  
  47. cout << "List1" << endl;
  48. for (int i = 1; i <= N; i++)
  49. {
  50. cout << "element :"; cin >> e; L1.push_back(e);
  51. }
  52.  
  53. cout << "List2" << endl;
  54. for (int i = 1; i <= N; i++)
  55. {
  56. cout << "element :"; cin >> e; L2.push_back(e);
  57. }
  58.  
  59. combine(L1, L2, L3);
  60.  
  61. cout << "The result is: ";
  62. for (int i = 0; i < N * 2; i++)
  63. {
  64. cout << L3[i] << " | ";
  65. } cout << endl;
  66.  
  67. }// end of main
Success #stdin #stdout 0s 4512KB
stdin
3 1 3 5 2 4 6
stdout
How many elements in each list?
List1
element :element :element :List2
element :element :element :comparison
The result is: 1 | 2 | 3 | 4 | 5 | 6 |