|
| 1 | +#include <bits/stdc++.h> |
| 2 | +using namespace std; |
| 3 | + |
| 4 | +// Merges two subarrays of arr[]. |
| 5 | +// First subarray is arr[left..mid] |
| 6 | +// Second subarray is arr[mid+1..right] |
| 7 | +void merge(vector<int>& arr, int left, |
| 8 | + int mid, int right) |
| 9 | +{ |
| 10 | + int n1 = mid - left + 1; |
| 11 | + int n2 = right - mid; |
| 12 | + |
| 13 | + // Create temp vectors |
| 14 | + vector<int> L(n1), R(n2); |
| 15 | + |
| 16 | + // Copy data to temp vectors L[] and R[] |
| 17 | + for (int i = 0; i < n1; i++) |
| 18 | + L[i] = arr[left + i]; |
| 19 | + for (int j = 0; j < n2; j++) |
| 20 | + R[j] = arr[mid + 1 + j]; |
| 21 | + |
| 22 | + int i = 0, j = 0; |
| 23 | + int k = left; |
| 24 | + |
| 25 | + // Merge the temp vectors back |
| 26 | + // into arr[left..right] |
| 27 | + while (i < n1 && j < n2) { |
| 28 | + if (L[i] <= R[j]) { |
| 29 | + arr[k] = L[i]; |
| 30 | + i++; |
| 31 | + } |
| 32 | + else { |
| 33 | + arr[k] = R[j]; |
| 34 | + j++; |
| 35 | + } |
| 36 | + k++; |
| 37 | + } |
| 38 | + |
| 39 | + // Copy the remaining elements of L[], |
| 40 | + // if there are any |
| 41 | + while (i < n1) { |
| 42 | + arr[k] = L[i]; |
| 43 | + i++; |
| 44 | + k++; |
| 45 | + } |
| 46 | + |
| 47 | + // Copy the remaining elements of R[], |
| 48 | + // if there are any |
| 49 | + while (j < n2) { |
| 50 | + arr[k] = R[j]; |
| 51 | + j++; |
| 52 | + k++; |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +// begin is for left index and end is right index |
| 57 | +// of the sub-array of arr to be sorted |
| 58 | +void mergeSort(vector<int>& arr, int left, int right) |
| 59 | +{ |
| 60 | + if (left >= right) |
| 61 | + return; |
| 62 | + |
| 63 | + int mid = left + (right - left) / 2; |
| 64 | + mergeSort(arr, left, mid); |
| 65 | + mergeSort(arr, mid + 1, right); |
| 66 | + merge(arr, left, mid, right); |
| 67 | +} |
| 68 | + |
| 69 | +// Function to print a vector |
| 70 | +void printVector(vector<int>& arr) |
| 71 | +{ |
| 72 | + for (int i = 0; i < arr.size(); i++) |
| 73 | + cout << arr[i] << " "; |
| 74 | + cout << endl; |
| 75 | +} |
| 76 | + |
| 77 | +// Driver code |
| 78 | +int main() |
| 79 | +{ |
| 80 | + vector<int> arr = { 12, 11, 13, 5, 6, 7 }; |
| 81 | + int n = arr.size(); |
| 82 | + |
| 83 | + cout << "Given vector is \n"; |
| 84 | + printVector(arr); |
| 85 | + |
| 86 | + mergeSort(arr, 0, n - 1); |
| 87 | + |
| 88 | + cout << "\nSorted vector is \n"; |
| 89 | + printVector(arr); |
| 90 | + return 0; |
| 91 | +} |
0 commit comments