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

Write C++ Programs For Sorting A Given List of Elements in Ascending Order Using Merge Sort The Following Sorting Methods

This C++ program uses merge sort to sort a list of integers in ascending order. It takes in a list of numbers from the user, calls the mergesort function to recursively split the list in half and sort each half, and then calls the merge function to merge the sorted halves back together into a fully sorted list which is then output to the user.

Uploaded by

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

Write C++ Programs For Sorting A Given List of Elements in Ascending Order Using Merge Sort The Following Sorting Methods

This C++ program uses merge sort to sort a list of integers in ascending order. It takes in a list of numbers from the user, calls the mergesort function to recursively split the list in half and sort each half, and then calls the merge function to merge the sorted halves back together into a fully sorted list which is then output to the user.

Uploaded by

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

/* Write C++ programs for sorting a given list of elements in ascending order using

Merge sort the following sorting methods */



#include<iostream>
#include<conio.h>
using namespace std;
void mergesort(int *,int,int);
void merge(int *,int,int,int);
int a[20],i,n,b[20];

main()
{
cout <<"\n enter no of elements";
cin >>n;
cout <<"enter the elements";
for(i=0;i<n;i++)
cin >>a[i];
mergesort(a,0,n-1);
cout <<" numbers after sort";
for(i=0;i<n;i++)
cout <<a[i] <<" ";
getch();
}

void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid);
mergesort(a,mid+1,j);
merge(a,i,mid,j);
}
}
void merge(int a[],int low,int mid ,int high)
{
int h,i,j,k;
h=low;
i=low;
j=mid+1;
while(h<=mid && j<=high)
{
if(a[h]<=a[j])
b[i]=a[h++];
else


b[i]=a[j++];
i++;
}

if( h >mid)
for(k=j;k<=high;k++)
b[i++]=a[k];
else
for(k=h;k<=mid;k++)
b[i++]=a[k];

cout <<"\n";
for(k=low;k<=high;k++)
{ a[k]=b[k];
cout <<a[k] <<" ";
}

}


OUTPUT
N enter no of elements8 12 5 61 60 50 1 70 81
enter the elements
5 12
60 61
5 12 60 61
1 50
70 81
1 50 70 81
1 5 12 50 60 61 70 81 numbers after sort1 5 12 50 60 61 70 81

You might also like