Professional Documents
Culture Documents
Ques 1 : Write a C/C++ program to sort a list of elements using the merge sort algorithm.
Note: Merge sort is an O(n log n) comparison-based sorting algorithm. Most implementations
produce a stable sort, which means that the implementation preserves the input order of equal
elements in the sorted output.
Code :
#include<iostream>
using namespace std;
void merge(int arra[],int l,int m,int r)
{
int i=l;
int j=m+1;
int k=l;
int temp[5];
while(i<=m&&j<=r)
{
if(arra[i]<=arra[j])
{
temp[k]=arra[i];
i++;
k++;
}
else
{
temp[k]=arra[j];
j++;
k++;
}
}
while(i<=m)
{
temp[k]=arra[i];
i++;
k++;
}
while(j<=r)
{
temp[k]=arra[j];
j++;
k++;
}
for(int p=l;p<=r;p++)
{
arra[p]=temp[p];
}
}
void mergesort(int arra[],int l,int r)
{
if(l<r)
{
int m=(l+r)/2;
mergesort(arra,l,m);
mergesort(arra,m+1,r);
merge(arra,l,m,r);
}
}
int main(){
cout<<"Enter 5 elements in the array: "<<endl;
int arr[5];
for(int i=0;i<5;i++){
cin>>arr[i];
}
mergesort(arr,0,4);