Merge sort
Overview
Mergesort is a recursive algorithm that splits an input of n elements into n subarrays
(each considered to be sorted as they have only 1 element)
then repeatedly merges them.
Any two sorted arrays can be sorted in linear time by iterating over each array and selecting the smaller element each time.
Visualization
Pseudocode
1:
procedure MergeSort(A) 2:
if ∣A∣=1 then 3:
4:
m←⌊2∣A∣⌋ 5:
L← MergeSort(A[...m]) 6:
R← MergeSort(A[m+1...]) 7:
return Merge(L,R) '
'
8:
procedure Merge(L,R) 9:
i,j,k←0 10:
while i<∣L∣ and j<∣R∣ do 11:
if l[i]<r[j] then 12:
A[k]←L[i] 13:
14:
15:
A[k]←R[j] 16:
17:
18:
while i<∣L∣ do 19:
A[k]←L[i] 20:
21:
22:
while j<∣R∣ do 23:
A[k]←R[j] 24:
25:
26:
Time Complexity
The time complexity of merge sort is Tn=T2n+n as at each iteration,
we divide the problem into two subproblems of half the size and merge them in linear time.
Therefore the time complexity is O(nlogn) by the master theorem.