Sunday, 26 April 2015

Cpp Program for sorting elements using merge sort


This a Cpp program which sorts all the elements using Merge Sort Technique.

Merge sort is a divide and conquer technique , here the element list is divided into half and that halves are again divided into halves until only 2 elements left . Then compare those 2 elements , smallest one is kept first, repeat the same process until are the halves are sorted , and repeat the same process but in reverse order to unite the element list into one again.




See the animation below,
Merge-sort-example-300px.gif
"Merge-sort-example-300px" by Swfung8 - Own work. Licensed under CC BY-SA 3.0 via Wikimedia Commons.



Download Code

PROGRAM : 
#include <iostream>
using namespace std;
void mergeSort(int [], int, int, int);
void partition(int [],int, int);
int main()
{
    int list[50];
    int i, n;

    cout << "How many numbers ? \t";
    cin >> n;
    cout << "\n\n";
    for(i = 0; i < n; i++)
    {
        cout << "Enter number  " << i+1 << ":\t";
        cin >> list[i];
    }
    partition(list, 0, n - 1);
    cout << "\n\nAfter merge sort:\n";
    for(i = 0; i < n; i++)
    {
        cout << list[i] << "\t";
    }
    cout << "\n\n";
    return 0;
}
void partition(int list[],int low,int high)
{
    int mid;

    if(low < high)
    {
        mid = (low + high) / 2;
        partition(list, low, mid);
        partition(list, mid + 1, high);
        mergeSort(list, low, mid, high);
    }
}

void mergeSort(int list[],int low,int mid,int high)
{
    int i, midd, k, loww, temp[50];

    loww = low;
    i = low;
    midd = mid + 1;
    while ((loww <= mid) && (midd <= high))
    {
        if (list[loww] <= list[midd])
        {
            temp[i] = list[loww];
            loww++;
        }
        else
        {
            temp[i] = list[midd];
            midd++;
        }
        i++;
    }
    if (loww > mid)
    {
        for (k = midd; k <= high; k++)
        {
            temp[i] = list[k];
            i++;
        }
    }
    else
    {
        for (k = loww; k <= mid; k++)
        {
            temp[i] = list[k];
            i++;
        }
    }

    for (k = low; k <= high; k++)
    {
        list[k] = temp[k];
    }
}


Download Code

OUTPUT : 
Cpp - Merge Sort