|
| 1 | +// Techie Delight https://www.techiedelight.com/merge-sort/ |
| 2 | + |
| 3 | +#include <iostream> |
| 4 | +#include <vector> |
| 5 | +#include <cstdlib> |
| 6 | +#include <algorithm> |
| 7 | + |
| 8 | +void print(const std::vector<int>& nums) |
| 9 | +{ |
| 10 | + for (auto n : nums) { |
| 11 | + std::cout << n << " "; |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +std::vector<int> generateRandomNumbers(const int length, const int min, const int max) |
| 16 | +{ |
| 17 | + std::vector<int> nums; |
| 18 | + for (int i = 0; i < length; ++i) { |
| 19 | + int x = min + (rand() % max - min + 1); |
| 20 | + nums.push_back(x); |
| 21 | + } |
| 22 | + return nums; |
| 23 | +} |
| 24 | + |
| 25 | +void merge(std::vector<int>& nums, std::vector<int>& aux, int low, int mid, int high) |
| 26 | +{ |
| 27 | + int i = low; |
| 28 | + int j = mid + 1; |
| 29 | + int k = low; |
| 30 | + |
| 31 | + while (i <= mid && j <= high) { |
| 32 | + if (nums[i] <= nums[j]) { |
| 33 | + aux[k++] = nums[i++]; |
| 34 | + } else { |
| 35 | + aux[k++] = nums[j++]; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + while (i <= mid) { |
| 40 | + aux[k++] = nums[i++]; |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | + while (j <= high) { |
| 45 | + aux[k++] = nums[j++]; |
| 46 | + } |
| 47 | + |
| 48 | + for (int i = low; i <= high; ++i) { |
| 49 | + nums[i] = aux[i]; |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +void mergesort(std::vector<int>& nums, std::vector<int>& aux, int low, int high) |
| 54 | +{ |
| 55 | + if (low == high) { |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + int mid = low + (high - low) / 2; |
| 60 | + mergesort(nums, aux, low, mid); |
| 61 | + mergesort(nums, aux, mid + 1, high); |
| 62 | + merge(nums, aux, low, mid, high); |
| 63 | +} |
| 64 | + |
| 65 | +void mergesort(std::vector<int>& nums) |
| 66 | +{ |
| 67 | + std::vector<int> aux(nums.size()); |
| 68 | + mergesort(nums, aux, 0, nums.size() - 1); |
| 69 | +} |
| 70 | + |
| 71 | +void test(std::vector<int>& nums) |
| 72 | +{ |
| 73 | + std::cout << "Numbers before sorting: "; |
| 74 | + print(nums); |
| 75 | + mergesort(nums); |
| 76 | + std::cout << "\nNumbers after sorting: "; |
| 77 | + print(nums); |
| 78 | + std::cout << "\nIs sorted: " << std::boolalpha << std::is_sorted(nums.begin(), nums.end()); |
| 79 | + std::cout << "\n"; |
| 80 | +} |
| 81 | + |
| 82 | +int main() |
| 83 | +{ |
| 84 | + std::vector<int> nums = generateRandomNumbers(20, -1000, 1000); |
| 85 | + test(nums); |
| 86 | + |
| 87 | + return 0; |
| 88 | +} |
0 commit comments