简体   繁体   中英

Number of Comparison in Worst Case of Merging Two Sorted Array?

Given two sorted arrays A, B with size n and m . I am looking for worst number of comparison that merges these two arrays.

1) n+m-1

2) max(n,m)

3)min (m,n)

4) mn

I know this is not a good question because the merge algorithm not mentioned, but i think, The normal merge sort algorithm - merge step with normally apply n + m -1 comparisons, where one list is of size n and and the other list is of size m. Using this algorithm is the most simplest approach to combine two sorted lists. any expert could help me, am I right by choosing (1)?

This can easily be found out from the documentation :

Complexity

At most std::distance(first1, last1) + std::distance(first2, last2) - 1 comparisons.

So No. 1 it is. (Yes it assumes that the standard committee got the complexity right, but that is not a stretch.)

Option 4 is obviously false because n + m - 1 grows slower than n*m, so we already have a better estimate.

Option 3 is false with this counterexample:

[4], [1, 2, 6, 7]

needs at least two comparisons. Option 2 counterexample:

[1,6], [2,5]

would need 3 comparisons:

1 < 2?, 6 < 2?, 6 < 5?

Assuming m < n, at least m comparisons and at most n+m-1 comparisons (worst case). So assuming all elements of the smallest list come first, the minimum number of comparisons is min (n, m). Assuming that by simplest you mean best case, then answer 3 is the correct answer. Answer 1 is correct for the worst case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM