# Visual C++ - Sorting Algorithm - Merge Sort Recursive

We often using sorting algorithm to sort numbers and strings. Also we have many sorting algorithms. I have explained here on how merge sort algorithm works.

The recusrive approach requires creatiion multi branch recursion until the elements are comparable by one iterm. The the merging happens with DoMerge function by taking three arguments - start, mid and right.

## Source Code

#include <iostream>

#include <string>

void DoMerge(int numbers[], int left, int mid, int right)

{

int temp;

int i, left_end, num_elements, tmp_pos;

left_end = (mid - 1);

tmp_pos = left;

num_elements = (right - left + 1);

while ((left <= left_end) && (mid <= right))

{

if (numbers[left] <= numbers[mid])

temp[tmp_pos++] = numbers[left++];

else

temp[tmp_pos++] = numbers[mid++];

}

while (left <= left_end)

temp[tmp_pos++] = numbers[left++];

while (mid <= right)

temp[tmp_pos++] = numbers[mid++];

for (i=0; i < num_elements; i++)

numbers[right--] = temp[right];

}

void MergeSort(int numbers[], int left, int right)

{

int mid;

if (right > left)

{

mid = (right + left) / 2;

MergeSort(numbers, left, mid);

MergeSort(numbers, (mid+1), right);

DoMerge(numbers, left, (mid+1), right);

}

}

void MergeSortHelper(int numbers[], int array_size)

{

MergeSort(numbers, 0, array_size - 1);

}

void max()

{

int max;

std::cout << "\nProgram for Ascending order of Numeric Values using MERGE SORT";

std::cout << "\n\nEnter the total number of elements: ";

std::cin >> max;

int *numarray = new int[max];

for(int i = 0; i < max; i++)

{

std::cout << "\nEnter [" << i + 1 << "] element: ";

std::cin >> numarray[i];

}

std::cout << "Before Sorting   : ";

for(int k = 0; k < max; k++)

std::cout << numarray[k] << " ";

std::cout << "\n";

MergeSortHelper(numarray,max);

std::cout << "\n\nThe numbers in ascending orders are given below:\n\n";

for(int i = 0; i < max; i++)

{

std::cout << "Sorted [" << i + 1 << "] element: ";

std::cout << numarray[i];

std::cout << "\n";

}

delete [] numarray;

}

## Output

Program for Ascending order of Numeric Values using MERGE SORT

Enter the total number of elements: 8

Enter  element: 80

Enter  element: 60

Enter  element: 40

Enter  element: 20

Enter  element: 10

Enter  element: 30

Enter  element: 50

Enter  element: 70

The numbers in ascending orders are given below:

Sorted  element: 10

Sorted  element: 20

Sorted  element: 30

Sorted  element: 40

Sorted  element: 50

Sorted  element: 60

Sorted  element: 70

Sorted  element: 80