merge sort

 #include<iostream>

using namespace std;
void merge(int a[],int l,int m,int u)
{
    int b[u];
    int i=l;
    int j=m+1;
    int k=l;
    while (i<=m&&j<=u)
    {
        if(a[i]<a[j])
        {
            b[k++]=a[i++];
        }
        else
        {
            b[k++]=a[j++];
        }
    }
    while (i<=m)
    {
        b[k++]=a[i++];
    }
    while (j<=u)
    {
        b[k++]=a[j++];
    }
    k=l;
    while(k<=u)
    {
        a[k]=b[k];
        k++;
    }
}
void mergesort(int a[],int l,int u)
{
    if(l<u)
    {
        int m=(l+u)/2;
        mergesort(a,l,m);
        mergesort(a,m+1,u);
        merge(a,l,m,u);
    }
}
int main()
{
    int arr[10], n, i;
    cout << "Enter the no. of elements: ";
    cin >> n;
    cout << "Enter the array elements: ";
    for (i = 0; i < n; i++)
    {
        cin >> arr[i];
    }
    mergesort(arr, 0, n - 1);
    cout << "array after sorting: ";
    for (i = 0; i < n; i++)
    {
        cout << arr[i] << " ";
    }
    return 0;
}

Comments

Popular Posts