ronith
5/29/2018 - 8:19 PM

merge sort

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int merge(int a[], int l, int m, int r){
    int n1 = m-l+1, n2 = r-m;
    int b[n1],c[n2];
    memcpy(b,a+l,n1*sizeof(int));
    memcpy(c,a+m+1,n2*sizeof(int));

    int i = 0, j = 0, k = l;
    while(i<n1 && j < n2){
        if (b[i] < c[j])
            a[k++] = b[i++];
        else
            a[k++] = c[j++];
    }
    while (i < n1)
        a[k++] = b[i++];
    while (j < n2)
        a[k++] = c[j++];
}

int mergesort(int a[], int l, int r){
    if(r>l){
        int m = (l+r)/2;
        mergesort(a,l,m);
        mergesort(a,m+1,r);
        merge(a, l,m,r);
    }
}

int main(){
    int n;
    cout << "No.of elements \n";
    cin >> n;
    int a[n];
    cout << "Enter the elements \n";
    for (int i = 0;i<n;i++)
        cin >> a[i];

    mergesort(a,0,n-1);
    for (int i = 0;i<n;i++)
        cout << a[i] << "  ";
}