Possible Duplicate:
Why Merge Operation in Merge Sort is O(n)?
why each iteration takes exactly O(n) regarding to the merge sort
could some one explain it for me in detail?
and why the C_merge(n)= O(n)? does it mean the time of merge two sorted array.
The idea is we have two sorted array, and not two array with one of them having it’s smallest element larger than that the other’s highest. What I meant to say is, it’s not
[1, 3, 9, 12]and[13, 17, 19]. But it’s more like[3, 12, 13, 17]and[1, 9, 19].You see, in later case you can’t append them. So, how do you combine? You follow the following algorithm:
melements, and the second hasn. You make an auxiliary array of sizem+n. This will store the final combined and sorted array.iandj, pointing to the heads of the arrays.iandj; choose the smaller one. Copy the value auxiliary array, and move the cursor at smaller cursor ahead.So, in our case, you compare
(3, [1]); ([3], 9); (12, [9]); ([12], 19); ([13], 19); ([17], 19); (--, [19]). You see? How may comparisons?(m+n). Assuming each operationO(1). The merge process for an array of length(m+n)isO(m+n).In best case, you will have sorted array as input. In such as, both the subarrays to be merged will just require joining. But we will apply the generic algorithm mentioned above. In that case, you will have to compare and copy
min(m,n)elements; and then copymax(m,n)elements to the auxiliary array. In any case, you are going to have total(m+n)operations.