0% found this document useful (0 votes)
20 views

Implementation of Merge Sort

The document provides an implementation of the Merge Sort algorithm in C++. It includes functions for merging two halves of an array and recursively sorting the array. The main function demonstrates the sorting of a sample vector and prints both the original and sorted vectors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Implementation of Merge Sort

The document provides an implementation of the Merge Sort algorithm in C++. It includes functions for merging two halves of an array and recursively sorting the array. The main function demonstrates the sorting of a sample vector and prints both the original and sorted vectors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Implementation of Merge Sort:

#include <bits/stdc++.h>
using namespace std;

void merge(vector<int>& arr, int left, int mid, int right)


{
int n1 = mid - left + 1;
int n2 = right - mid;

vector<int> L(n1), R(n2);

for (int i = 0; i < n1; i++)


L[i] = arr[left + i];
for (int j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

int i = 0, j = 0;
int k = left;

while (i < n1 && j < n2) {


if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1) {


arr[k] = L[i];
i++;
k++;
}

while (j < n2) {


arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(vector<int>& arr, int left, int right)


{
if (left >= right)
return;

int mid = left + (right - left) / 2;


mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
void printVector(vector<int>& arr)
{
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
cout << endl;
}

int main()
{
vector<int> arr = { 12, 11, 13, 5, 6, 7 };
int n = arr.size();

cout << "Given vector is \n";


printVector(arr);

mergeSort(arr, 0, n - 1);

cout << "\nSorted vector is \n";


printVector(arr);
return 0;
}

You might also like