Thursday 18 October 2018

Merge sorting program in C++

#include <iostream>

using namespace std;
/****************************************************************************************************/
void merg(int *arr,int first,int last)
{
    int mid=(first+last)/2;
 int i=first;
 int j=mid+1;
 int k=first;
 int temp[100];

    while(i<=mid && j<=last)
    {
        if(arr[i]<arr[j])
            {
            temp[k++]=arr[i++];
            }
        else
            {
                temp[k++]=arr[j++];
            }
    }
        while(i<=mid)
        {
            temp[k++]=arr[i++];
        }
            while(j<=mid)
            {
                temp[k++]=arr[j++];
            }
    for(int i=first;i<=last;i++)
    {
        arr[i]=temp[i];
    }
}
/*********************************************************************************************************/
void mergesort(int arr[],int first,int last)
{
    if(first>=last)
    {
        return;
    }

    int mid=(first+last)/2;

    mergesort(arr,first,mid);
    mergesort(arr,mid+1,last);

    merg(arr,first,last);
}
/**************************************************************************************************************/

int main()
{
    int arr[100];
    int n;
    cout<<"Enter number of elements in array:"<<endl;
    cin>>n;
    cout<<"Enter numbers to be sort:"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    mergesort(arr,0,n-1);
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}

0 comments:

Post a Comment