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

program For Merge Sort

The document describes a C++ program that implements merge sort to sort an array of integers. It takes in an unsorted array as input, calls the mergesort function which recursively divides the array into single elements and then calls the merge function to merge the sorted subarrays back together into a fully sorted array. The sorted array is then output to demonstrate that the merge sort algorithm works correctly.

Uploaded by

Shubham Jain
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views2 pages

program For Merge Sort

The document describes a C++ program that implements merge sort to sort an array of integers. It takes in an unsorted array as input, calls the mergesort function which recursively divides the array into single elements and then calls the merge function to merge the sorted subarrays back together into a fully sorted array. The sorted array is then output to demonstrate that the merge sort algorithm works correctly.

Uploaded by

Shubham Jain
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

//PROGRAM FOR MERGE SORT

#include<iostream.h>
#include<conio.h>
void mergesort(int[],int,int);
void merge(int[],int,int,int);
void main()
{
int a[10],p,q,r,i,n;
clrscr();
cout<<"Enter the number of elements";
cin>>n;
p=0;
r=n-1;
cout<<"Enter the array";
for(i=0;i<n;i++)
{
cin>>a[i];
}
mergesort(a,p,r);
cout<<"The sorted array is:";
for(i=0;i<n;i++)
{
cout<<"\n"<<a[i];
}
getch();
}
void mergesort(int a[],int p,int r)
{
if( p < r)
{
int q=(p+r)/2;
mergesort(a,p,q);
mergesort(a,q+1,r) ;
merge(a,p,q,r);
}
}
void merge(int a[],int p,int q,int r)
{
int c[10];
int i=p;
int j=q+1;
int k=p;
while((i<=q)&&(j<=r))
{

if(a[i]<a[j])
{
c[k]=a[i];
i=i+1;
k=k+1;
}
else
{
c[k]=a[j];
j=j+1;
k=k+1;
}
}
while(i<=q)
{
c[k] =a[i];
i=i+1;
k=k+1;
}
while(j<=r)
{
c[k]=a[j];
j=j+1;
k=k+1;
}
int l=p;
while(l<=r)
{
a[l]=c[l];
l=l+1;
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy