Advertisement
informaticage

merge sort implementation with vectors

Mar 14th, 2023
951
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. std::vector<int> merge(std::vector<int> &A, std::vector<int> &B) {
  5.   std::vector<int> M;
  6.   int i = 0, j = 0;
  7.  
  8.   while (i < A.size() && j < B.size()) {
  9.     if (A.at(i) <= B.at(j)) {
  10.       M.push_back(A.at(i));
  11.       i++;
  12.     } else {
  13.       M.push_back(B.at(j));
  14.       j++;
  15.     }
  16.   }
  17.  
  18.   while (i < A.size()) {
  19.     M.push_back(A.at(i));
  20.     i++;
  21.   }
  22.  
  23.   while (j < B.size()) {
  24.     M.push_back(B.at(j));
  25.     j++;
  26.   }
  27.  
  28.   return M;
  29. }
  30.  
  31. std::vector<int> merge_sort(std::vector<int> &nums) {
  32.   std::cout << nums.size() << " " << std::endl;
  33.   std::cin.get();
  34.   // Splitto nums in due
  35.   if (nums.size() == 1) {
  36.     return nums;
  37.   }
  38.  
  39.   // Prima metá di nums
  40.   std::vector<int> left =
  41.       std::vector<int>(nums.begin(), nums.begin() + (nums.size() / 2));
  42.  
  43.   left = merge_sort(left);
  44.  
  45.   // Seconda metá di nums
  46.   std::vector<int> right =
  47.       std::vector<int>(nums.begin() + (nums.size() / 2), nums.end());
  48.  
  49.   right = merge_sort(right);
  50.  
  51.   return merge(left, right);
  52. }
  53.  
  54. int main() {
  55.   std::vector<int> nums = {1, 2, 3, 4, 1, 6, 56, 3, -1};
  56.  
  57.   std::vector<int> A = {1, 3, 6, 7, 9, 11, 23};
  58.   std::vector<int> B = {8, 9, 10, 12, 14, 22};
  59.  
  60.   std::vector<int> C = merge(A, B);
  61.  
  62.   std::vector<int> sorted = merge_sort(nums);
  63.   for (int x : sorted) {
  64.     std::cout << x << " ";
  65.   }
  66.  
  67.   return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement