merge sort merge code example
Example 1: merge sort
#include <iostream>
using namespace std;
void merge(int arr[],int start,int mid,int end)
{
int n1=mid-start+1;
int n2=end-mid;
int l[n1],m[n2];
for(int i=0;i<n1;i++)
{
l[i]=arr[start+i];
}
for(int j=0;j<n2;j++)
{
m[j]=arr[mid+1+j];
}
int i=0;
int j=0;
int k=start;
while(i<n1&&j<n2)
{
if(l[i]<m[j])
{
arr[k]=l[i];
k++;
i++;
}
else
{
arr[k]=m[j];
k++;
j++;
}
}
while(i<n1)
{
arr[k]=l[i];
k++;
i++;
}
while(j<n2)
{
arr[k]=m[j];
k++;
j++;
}
}
void mergesort(int arr[],int start,int end)
{
if(start<end)
{
int mid=(start+end)/2;
mergesort(arr,start,mid);
mergesort(arr,mid+1,end);
merge(arr,start,mid,end);
}
}
void display(int arr[],int n)
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main()
{
int n;
cout<<"enter the size of the array:"<<endl;
cin>>n;
cout<<"enter the elements of the array:"<<endl;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"array as it is:"<<endl;
display(arr,n);
cout<<"sorted array:"<<endl;
mergesort(arr,0,n-1);
display(arr,n);
return 0;
}
Example 2: merge sort
# Python3 recursive merge sort algorithm -> O(n*log(n))
def merge_sort(A):
def merge(l, r):
i = j = 0
n = [] # merging container
while i < len(l) or j < len(r):
# if no more elements to the right,
# add remaining left elements
if i == len(l):
n.extend(r[j:])
break
# if no more elements to the left,
# add remaining right elements
if j == len(r):
n.extend(l[i:])
break
# if elements left on both sides,
# add smaller element
a, b = l[i], r[j]
if a < b:
n.append(a)
i += 1
else:
n.append(b)
j += 1
return n
# divide list down to single-elements
s = len(A)
if s > 1:
s
l = merge_sort(A[:s]) # split left
r = merge_sort(A[s:]) # split right
return merge(l, r) # merge sides in order
else:
return A