The Merge Sort algorithm is a sorting algorithm that is considered as an example of the divide and conquer strategy. So, in this algorithm, the array is initially divided into two equal halves and then they are combined in a sorted manner. We can think of it as a recursive algorithm that 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, we split the array into halves and recursively invoke the merge sort on each of the halves. Finally, when both the 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.
C++ Code for Merge Sort function:
voidmerge_sort(intA[], intl, intr){ // only one elementif (l >= r) return;int mid = l + r >> 1; // Recursively sort on the left and right.merge_sort(A, l, mid);merge_sort(A, mid + 1, r); // Merge two separate lists int k = 0, i = l, j = mid + 1;while (i <= mid && j <= r)if (A[i] <= A[j]) tmp[k ++] = A[i ++];elsetmp[k ++] = A[j ++]; // add all remaining elementswhile (i <= mid) tmp[k ++] = A[i ++];while (j <= r) tmp[k ++] = A[j ++]; // move elements from tmp to original arrayfor (i = l, j = 0; i <= r; i++, j++) A[i] = tmp[j];}