MergeSort
Mergesort is a sorting algorithm that works by dividing an array into smaller subarrays, sorting each subarray, and then merging the
sorted subarrays back together to form the final sorted array.
In simple terms, we can say that the process of merge sort is to divide the array into two halves, sort each half, and then merge the
sorted halves back together. This process is repeated until the entire array is sorted.
Merge sort is a popular choice for sorting large datasets because it is relatively efficient and easy to implement. It is often used in
conjunction with other algorithms, such as quicksort, to improve the overall performance of a sorting routine.
MergeSort Working Process:
Think of it as a recursive algorithm continuously splits the array in half until it cannot be further divided. This means that if the array
becomes empty or has only one element left, the dividing will stop, i.e. it is the base case to stop the recursion. If the array has
multiple elements, split the array into halves and recursively invoke the merge sort on each of the halves. Finally, when both halves
are sorted, the merge operation is applied. Merge operation is the process of taking two smaller sorted arrays and combining them
to eventually make a larger one.
Illustration:
To know the functioning of merge sort, let’s consider an array arr[] = {38, 27, 43, 3, 9, 82, 10}
At first, check if the left index of array is less than the right          After dividing the array into smallest units, start merging the
index, if yes then calculate its mid-point                                 elements again based on comparison of size of elements
                                                                           Firstly, compare the element for each list and then combine
                                                                           them into another list in a sorted manner.
Now, as we already know that merge sort first divides the
whole array iteratively into equal halves, unless the atomic
values are achieved.
Here, we see that an array of 7 items is divided into two                 After the final merging, the list looks like this:
arrays of size 4 and 3 respectively.
Now, again find that is left index is less than the right index
for both arrays, if found yes, then again calculate mid points
for both the arrays.
                                                                          The following diagram shows the complete merge sort
                                                                          process for an example array {38, 27, 43, 3, 9, 82, 10}.
Now, further divide these two arrays into further halves, until
the atomic units of the array are reached and further division
is not possible.
Implementation
// C++ program for Merge Sort                                }
#include <iostream>
using namespace std;                                         // begin is for left index and end is
                                                             // right index of the sub-array
// Merges two subarrays of array[].                          // of arr to be sorted */
// First subarray is arr[begin..mid]                         void mergeSort(int array[], int const begin, int const end)
// Second subarray is arr[mid+1..end]                        {
void merge(int array[], int const left, int const mid,          if (begin >= end)
       int const right)                                            return; // Returns recursively
{
   auto const subArrayOne = mid - left + 1;                      auto mid = begin + (end - begin) / 2;
   auto const subArrayTwo = right - mid;                         mergeSort(array, begin, mid);
                                                                 mergeSort(array, mid + 1, end);
  // Create temp arrays                                          merge(array, begin, mid, end);
  auto *leftArray = new int[subArrayOne],                    }
     *rightArray = new int[subArrayTwo];
                                                             // UTILITY FUNCTIONS
  // Copy data to temp arrays leftArray[] and rightArray[]   // Function to print an array
  for (auto i = 0; i < subArrayOne; i++)                     void printArray(int A[], int size)
     leftArray[i] = array[left + i];                         {
  for (auto j = 0; j < subArrayTwo; j++)                        for (auto i = 0; i < size; i++)
     rightArray[j] = array[mid + 1 + j];                          cout << A[i] << " ";
                                                             }
  auto indexOfSubArrayOne
    = 0, // Initial index of first sub-array                 // Driver code
    indexOfSubArrayTwo                                       int main()
    = 0; // Initial index of second sub-array                {
  int indexOfMergedArray                                        int arr[] = { 12, 11, 13, 5, 6, 7 };
    = left; // Initial index of merged array                    auto arr_size = sizeof(arr) / sizeof(arr[0]);
                                                                cout << "Given array is \n";
  // Merge the temp arrays back into array[left..right]         printArray(arr, arr_size);
  while (indexOfSubArrayOne < subArrayOne
        && indexOfSubArrayTwo < subArrayTwo) {                   mergeSort(arr, 0, arr_size - 1);
     if (leftArray[indexOfSubArrayOne]
        <= rightArray[indexOfSubArrayTwo]) {                     cout << "\nSorted array is \n";
        array[indexOfMergedArray]                                printArray(arr, arr_size);
           = leftArray[indexOfSubArrayOne];                      return 0;
        indexOfSubArrayOne++;                                }
     }
     else {                                                  // This code is contributed by Mayank Tyagi
        array[indexOfMergedArray]                            // This code was revised by Joshua Estes
           = rightArray[indexOfSubArrayTwo];
        indexOfSubArrayTwo++;
     }
     indexOfMergedArray++;
  }
  // Copy the remaining elements of
  // left[], if there are any
  while (indexOfSubArrayOne < subArrayOne) {
     array[indexOfMergedArray]
        = leftArray[indexOfSubArrayOne];
     indexOfSubArrayOne++;
     indexOfMergedArray++;
  }
  // Copy the remaining elements of
  // right[], if there are any
  while (indexOfSubArrayTwo < subArrayTwo) {
     array[indexOfMergedArray]
        = rightArray[indexOfSubArrayTwo];
     indexOfSubArrayTwo++;
     indexOfMergedArray++;
  }
  delete[] leftArray;
  delete[] rightArray;
Activity 1
         3        2        -3        -2        4        1
Activity 2
       -4    -1       -3        -5        -6       -2   -7
Activity 3
      5       7       8       1   9       3       2       4
Activity 4
          8       9       3           1       4       5