You are on page 1of 3

PRACTICAL- 2.

Name : KAMAL NATH


UID : 20BCS2011
Branch BE-CSE
Subject : DSA LAB
Semester : 3rd
Date: 07-10-2021
Section: CSE8-A

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];
}

cout<<"Before merge sort: "<<endl;


for(int i=0;i<5;i++){
cout<<arr[i]<<" ";
}

mergesort(arr,0,4);

cout<<endl<<"After merge sort:"<<endl;


for(int i=0;i<5;i++){
cout<<arr[i]<<" ";
}
return 0;
}
Output :

You might also like