Merge Sort
{Divide - Conquer}
Merge Sort is a Divide and Conquer algorithm.
It divides input array in to two halves, calls itself for the two halves, and then merges the two sorted halves.
{Divide - Conquer}
Merge Sort is a Divide and Conquer algorithm.
It divides input array in to two halves, calls itself for the two halves, and then merges the two sorted halves.
1) Algorithm:
MergeSort(arr[], l, r):
If r > l:
Find the middle point to divide the array into two halves: middle: m = l+ (r-l)/2
Call mergeSort for first half: Call mergeSort(arr, l, m)
Call mergeSort for second half: Call mergeSort(arr, m+1, r)
Merge the two halves sorted in step 2 and 3: Call merge(arr, l, m, r)
The merge() function is used for merging two halves.
The merge(arr, l, m, r) is a key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one.
The Mergesort() function recuresively calls itself to divide the aary till size becomes one.
Why m = l + (r-l)/2 ?
MAX_VALUE . The addition is performed first before the division. Adding two max values lead Integer overflow exception. Thats why we use L+((R-L)/2) to save the code from Integer overflow.
2) Code:
3) Running Time:
Time Complexity:
Sorting arrays on different machines. Merge Sort is a recursive algorithm and time complexity can be expressed as following recurrence relation.
T(n) = 2T(n/2) + θ(n)
Time complexity of Merge Sort is θ(nlogn) in all 3 cases (worst, average and best) as merge sort always divides the array into two halves and takes linear time to merge two halves.
4) Analysis:
Auxiliary Space: O(n)
Algorithmic Paradigm: Divide and Conquer
Sorting In Place: No in a typical implementation
Stable: Yes
Drawbacks of Merge Sort:
Slower comparative to the other sort algorithms for smaller tasks.
Merge sort algorithm requires an additional memory space of 0(n) for the temporary array.
It goes through the whole process even if the array is sorted.