Monday, June 29, 2015

C++ program to implement Merge Sort

/*-------------------------------------------------------------------------------------------------------------
File Name:      merge.cpp
Author:           sujith
Program:        Write a C++ program to implement Merge Sort
Date:               21-04-2015
--------------------------------------------------------------------------------------------------------------*/

#include<iostream>
#include<stdio.h>
using namespace std;
void mergesort(int a[20],int n);

int main()
{

        int i,n,a[20];
        cout<<"Enter the total number of element\n";
        cin>>n;
        cout<<"Enter the Elements\n";
        for(i=0;i<n;i++)
        {
                cin>>a[i];
        }
        cout<<"After sorting\n";
        mergesort(a,n);
        for(i=0;i<n;i++){
        cout<<a[i]<<"\n";
        }
}
void mergesort(int a[20],int n)
{
        int aux[20],i,j,k,l1,l2,u1,u2,size;
        size=1;
        while(size<n)
        {
        l1=0;
        k=0;
        while(l1+size<n)
        {
                l2=l1+size;
                u1=l2-1;
                u2=(l2+size-1<n)?l2+size-1:n-1;
        for(i=l1,j=l2;i<=u1&&j<=u2;k++)
        {
                if(a[i]<=a[j]){
                        aux[k]=a[i++];
                }else{
                        aux[k]=a[j++];
                }
        }
        for(;i<=u1;k++){
                aux[k]=a[i++];
        }
        for(;j<=u2;k++){
                aux[k]=a[j++];
        }
                l1=u2+1;
        }
        for(i=l1;i<n;i++)
                aux[k++]=a[i];
        for(i=0;i<n;i++)
                a[i]=aux[i];
                size=size*2;
        }
}




OUTPUT:

[141740@localhost ~]$ g++ merge.cpp
[141740@localhost ~]$ ./a.out
Enter the total number of element
5
Enter the Elements
11        33        55        22        88
After sorting
11
22
33
55

88

No comments:

Post a Comment