For merge-sort divide and conquer operations, how much time is required in bottom up merging phase? My instructor says that it is be linear, hence it will be
O(n). But I didn’t get it. How will it be linear?
How will merging operation be linear O(n)?
Merge operation of two arrays, is scanning arrays and picking the lowest/highest of two.
so you have
you compare like this (sort of pseudo code)
you see if array
a[k], andb[m]the sum of iterations by the three loops will bek+m.In case
Here is the first loop for this:
The second loop does not run since
ais already scanned.The third loop appends
You see
8 = 4 + 4loops running? What’s the orderO(n).In Mergesort the divide operation is logarithmic,
ln n— the merge part is linear. Since you divide and merge back the order becomes multiplicative so Mergesort isO(nln(n)).Unlike Bubble, Selection, Insertion sort where you scan left to right (O(n)) and then fit the right candidate by consecutive swaps (bubble), or by scanning the minimum in rest of the the unsorted array (selection), or by inserting at right place in sorted part of the array (insertion) — these operations are O(n)… so the overall order of these algos becomes O(n2)