Merge Sort

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Write a program for Merge Sort

Algorithm:

 Create a function called merge_sort that accepts a list of integers as its


argument. All following instructions presented are within this function.
 Start by dividing the list into halves. Record the initial length of the list.
 Check that the recorded length is equal to 1. If the condition evaluates to true,
return the list as this means that there is just one element within the list.
Therefore, there is no requirement to divide the list.
 Obtain the midpoint for a list with a number of elements greater than 1. When
using the Python language, the // performs division with no remainder. It
rounds the division result to the nearest whole number. This is also known as
floor division.
 Using the midpoint as a reference point, split the list into two halves. This is
the divide aspect of the divide-and-conquer algorithm paradigm.
 Recursion is leveraged at this step to facilitate the division of lists into halved
components. The variables ‘left_half’ and ‘right_half’ are assigned to the
invocation of the ‘merge_sort’ function, accepting the two halves of the initial
list as parameters.
 The ‘merge_sort’ function returns the invocation of a function that merges two
lists to return one combined, sorted list.
Program:

#include <stdio.h>
#define max 100
int merge(int a[],int mid,int low,int high)
{
int i,j,k,b[100];
i=low;
j=mid+1;
k=low;
while(i<=mid&&j<=high)
{
if(a[i]<a[j])
{
b[k]=a[i];
i++;
k++;
}
else
{
b[k]=a[j];
j++;
k++;
}
}
while(i<=mid)
{
b[k]=a[i];
k++;
i++;
}
while(j<=high)
{
b[k]=a[j];
k++;
j++;
}
for(int i=low;i<=high;i++)
{
a[i]=b[i];
}
}
int mergesort(int a[],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,mid,low,high);
}
}
int main()
{
int a[max],n,i;
printf("Enter The Number Of Elements In The List...:\n");
scanf("%d",&n);
printf("Enter %d Numbers...:\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("After Merge Sorting The Elements Are As Follows:\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
printf("\n");
return 0;
}

Output:
Enter The Number Of Elements In The List...:
5
Enter 5 Numbers...:
225
196
169
144
121
After Merge Sorting The Elements Are As Follows:
121
144
169
196
225

You might also like