Saturday, May 18, 2013

Merge sort C++ code

For in-depth understanding of Data Structure and Algorithm concepts refer :

1) INTRODUCTION TO ALGORITHMS by Coremen Introduction to Algorithms, 3rd Edition From flipkart.com
Introduction to Algorithms, 3rd Edition From amazon.com
Introduction to Algorithms from amazon.in

2) DATA STRUCTURES USING C AND C++ by Tenenbaum M Aaron - DATA STRUCTURES USING C AND C++ by Tenenbaum M Aaron from flipkart.com
Data Structures Using C and C++ (2nd Edition) from amazon.com
Data Structures Using C and C++ from amazon.in

#include<iostream.h>
#include<conio.h>
void merge(int a[], int p, int q, int r)
{
    int i,j;
    int n1, n2;
    n1=q-p+1;
    n2=r-q;
    int L[21], R[21];
    for(int i=0; i<n1; i++)
        L[i]=a[p+i];
    for(int j=0; j<n2; j++)
        R[j]=a[q+j+1];
    L[n1]=999;
    R[n2]=999;
    i=0; j=0;
    for(int k=p; k<=r; k++)
    {
        if(L[i]<=R[j])
        {
            a[k]=L[i];
            i++;
        }

        else
        {
            a[k]=R[j];
            j++;
        }
    }
}
void merge_sort(int a[], int p,int r)
{
    int q;
    if(p<r)
    {
        q=(p+r)/2;
        merge_sort(a, p, q);
        merge_sort(a, q+1, r);
        merge(a, p, q, r);
    }
}

void main()
{
    int a[20],n;
    cout<<"Enter the size of the array: "  ;
    cin>>n;
    cout<<"ENTER ARRAY ELEMENTS: \n";
    for(int i=0; i<n; i++)
        cin>>a[i];
    merge_sort(a,0,n-1);
    cout<<"YOUR SORTED ARRAY IS: \n";
    for(int i=0;i<n;i++)
        cout<<a[i]<<endl;
    getch();}



No comments:

Post a Comment