Why Merge Operation in Merge Sort is O(n)?

江枫思渺然 提交于 2019-12-02 03:12:43

Merge operation of two arrays, is scanning arrays and picking the lowest/highest of two.

so you have

a: [1, 3, 6, 7]
b: [4, 5, 7, 8]

you compare like this (sort of pseudo code)

indexA = 0;
indexB = 0;
auxilaryArray = [];
indexAux = 0;

while true 
   if indexA > len(a)-1 or indexb > len(b) -1  
       break
   # you are cherry picking one from the two array which is lesser
   # until any one of these array exausts
   if(a[indexA] > b[indexB])
       auxilaryArray[indexAux++] = b[indexB++]
   else
       auxilaryArray[indexAux++] = a[indexA++]

#append the remaining array 
while indexA < len(a)
    auxilaryArray[indexAux++] = a[indexA++]

#appends the remaining array
while indexB < len(b)
    auxilaryArray[indexAux++] = b[indexB++]

you see if array a[k], and b[m] the sum of iterations by the three loops will be k+m.


In case

a: [1, 3, 6, 7]
b: [4, 5, 7, 8]

Here is the first loop for this:

(0, 0), (1, 0), (2, 0), (2, 1), (2, 2), (3, 2) # 6 iterations; array a exhausted

The second loop does not run since a is already scanned.

The third loop appends

b[2], b[3]   # 2 iterations; b exhaused

You see 8 = 4 + 4 loops running? What's the order O(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 is O(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)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!