Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- std::vector<int> merge(std::vector<int> &A, std::vector<int> &B) {
- std::vector<int> M;
- int i = 0, j = 0;
- while (i < A.size() && j < B.size()) {
- if (A.at(i) <= B.at(j)) {
- M.push_back(A.at(i));
- i++;
- } else {
- M.push_back(B.at(j));
- j++;
- }
- }
- while (i < A.size()) {
- M.push_back(A.at(i));
- i++;
- }
- while (j < B.size()) {
- M.push_back(B.at(j));
- j++;
- }
- return M;
- }
- std::vector<int> merge_sort(std::vector<int> &nums) {
- std::cout << nums.size() << " " << std::endl;
- std::cin.get();
- // Splitto nums in due
- if (nums.size() == 1) {
- return nums;
- }
- // Prima metá di nums
- std::vector<int> left =
- std::vector<int>(nums.begin(), nums.begin() + (nums.size() / 2));
- left = merge_sort(left);
- // Seconda metá di nums
- std::vector<int> right =
- std::vector<int>(nums.begin() + (nums.size() / 2), nums.end());
- right = merge_sort(right);
- return merge(left, right);
- }
- int main() {
- std::vector<int> nums = {1, 2, 3, 4, 1, 6, 56, 3, -1};
- std::vector<int> A = {1, 3, 6, 7, 9, 11, 23};
- std::vector<int> B = {8, 9, 10, 12, 14, 22};
- std::vector<int> C = merge(A, B);
- std::vector<int> sorted = merge_sort(nums);
- for (int x : sorted) {
- std::cout << x << " ";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement