#include <bits/stdc++.h>
using namespace std;
void merge(vector<int> &arr, int low, int mid, int high) {
vector<int> temp; // temporary array
int left = low; // starting index of left half of arr
int right = mid + 1; // starting index of right half of arr
//storing elements in the temporary array in a sorted manner//
while (left <= mid && right <= high) {
if (arr[left] <= arr[right]) {
temp.push_back(arr[left]);
left++;
}
else {
temp.push_back(arr[right]);
right++;
}
}
// if elements on the left half are still left //
while (left <= mid) {
temp.push_back(arr[left]);
left++;
}
// if elements on the right half are still left //
while (right <= high) {
temp.push_back(arr[right]);
right++;
}
// transfering all elements from temporary to arr //
for (int i = low; i <= high; i++) {
arr[i] = temp[i - low];
}
}
void mergeSort(vector<int> &arr, int low, int high) {
if (low >= high) return;
int mid = (low + high) / 2 ;
mergeSort(arr, low, mid); // left half
mergeSort(arr, mid + 1, high); // right half
merge(arr, low, mid, high); // merging sorted halves
}
int main() {
vector<int> arr = {9, 4, 7, 6, 3, 1, 5} ;
int n = 7;
cout << "Before Sorting Array: " << endl;
for (int i = 0; i < n; i++) {
cout << arr[i] << " " ;
}
cout << endl;
mergeSort(arr, 0, n - 1);
cout << "After Sorting Array: " << endl;
for (int i = 0; i < n; i++) {
cout << arr[i] << " " ;
}
cout << endl;
return 0 ;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgp2b2lkIG1lcmdlKHZlY3RvcjxpbnQ+ICZhcnIsIGludCBsb3csIGludCBtaWQsIGludCBoaWdoKSB7CiAgICB2ZWN0b3I8aW50PiB0ZW1wOyAvLyB0ZW1wb3JhcnkgYXJyYXkKICAgIGludCBsZWZ0ID0gbG93OyAgICAgIC8vIHN0YXJ0aW5nIGluZGV4IG9mIGxlZnQgaGFsZiBvZiBhcnIKICAgIGludCByaWdodCA9IG1pZCArIDE7ICAgLy8gc3RhcnRpbmcgaW5kZXggb2YgcmlnaHQgaGFsZiBvZiBhcnIKCiAgICAvL3N0b3JpbmcgZWxlbWVudHMgaW4gdGhlIHR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