0% found this document useful (0 votes)
4 views2 pages

Merge Sort Algo

The document contains C++ code implementing the merge sort algorithm for both arrays and vectors. It defines functions to merge two sorted halves and recursively sort the array or vector. The merge function combines the sorted subarrays into a single sorted array.

Uploaded by

dedod85167
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Merge Sort Algo

The document contains C++ code implementing the merge sort algorithm for both arrays and vectors. It defines functions to merge two sorted halves and recursively sort the array or vector. The merge function combines the sorted subarrays into a single sorted array.

Uploaded by

dedod85167
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include<vector>

using namespace std;


void merge(int arr[],int s,int e){
int mid = s + (e-s)/2;
int l1 = mid-s +1, l2 = e-mid ;
int arr1[l1],arr2[l2];
int k = s;
for(int i=0;i<l1;i++){
arr1[i] = arr[k++];
}
k = mid+1;
for(int i=0;i<l2;i++){
arr2[i] = arr[k++];
}
int i=0,j=0;
k=s;
while(i<l1 && j<l2){
if(arr1[i]>arr2[j]){
arr[k++] = arr2[j++];
}
else
arr[k++] = arr1[i++];
}
while(i<l1){
arr[k++] = arr1[i++];
}
while(j<l2){
arr[k++] = arr2[j++];
}
}
void sort(int arr[],int s,int e){
if(s>=e){
return;
}
int mid = s+ (e-s)/2;
//left sort
sort(arr,s,mid);
//right sort
sort(arr,mid+1,e);
merge(arr,s,e);
}
void merge(vector<int> arr[],int s,int e){
int mid = s + (e-s)/2;
int l1 = mid-s +1, l2 = e-mid ;
int *arr1=new int[l1],*arr2 = new int[l2];
int k = s;
for(int i=0;i<l1;i++){
arr1[i]=(arr[k++]);
}
k = mid+1;
for(int i=0;i<l2;i++){
arr2[i]=(arr[k++]);
}
int i=0,j=0;
k=s;
while(i<l1 && j<l2){
if(arr1[i]>arr2[j]){
arr[k++] = arr2[j++];
}
else
arr[k++] = arr1[i++];
}
while(i<l1){
arr[k++] = arr1[i++];
}
while(j<l2){
arr[k++] = arr2[j++];
}
}
void sort(vector<int> arr[],int s,int e){
if(s>=e){
return;
}
int mid = s+ (e-s)/2;
//left sort
sort(arr,s,mid);
//right sort
sort(arr,mid+1,e);
merge(arr,s,e);
}
void mergeSort(int arr[], int l, int r) {
sort(arr,l,r);
}

You might also like