Advertisement
whitesurge

Lab 3 Merge and Sor

Feb 14th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. /******************************************************************************
  2.  
  3.                               Online C++ Compiler.
  4.                Code, Compile, Run and Debug C++ program online.
  5. Write your code in this editor and press "Run" button to compile and execute it.
  6.  
  7. *******************************************************************************/
  8.  
  9. #include <iostream>
  10. #include <fstream>
  11. #include <cstdlib>
  12.  
  13.  
  14. #include <bits/stdc++.h>
  15. using namespace std;
  16.  
  17. // Function to merge array in sorted order
  18. void sortedMerge(int a[], int b[], int res[],  
  19.                                 int n, int m)
  20. {
  21.     // Concatenate two arrays
  22.     int i = 0, j = 0, k = 0;
  23.     while (i < n) {
  24.         res[k] = a[i];
  25.         i += 1;
  26.         k += 1;
  27.     }
  28.     while (j < m) {
  29.         res[k] = b[j];
  30.         j += 1;
  31.         k += 1;
  32.     }
  33.  
  34.     // sorting the res array
  35.     sort(res, res + n + m);
  36. }
  37.  
  38. // Driver code
  39. int main()
  40. {
  41.     int a[] = { 25, 10, 5, 15 };
  42.     int b[] = { 20, 3, 2, 12 };
  43.     int n = sizeof(a) / sizeof(a[0]);
  44.     int m = sizeof(b) / sizeof(b[0]);
  45.  
  46.     // Final merge list
  47.     int res[n + m];
  48.     sortedMerge(a, b, res, n, m);
  49.  
  50.     cout << "Sorted merged list :";
  51.     for (int i = 0; i < n + m; i++)
  52.         cout << " " << res[i];
  53.     cout << "";
  54.  
  55.     return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement