Data Structures and Algorithms

In merge sort, the two sorted runs 1, 4, 7, 9 and 2, 3, 8, 10 are merged into one by repeatedly comparing their front elements and outputting the smaller. When one run is empty, the rest of the other is output without comparisons. How many comparisons are made?

  1. A4
  2. B7
  3. C8
Show answer and explanation

Answer: B. 7

The comparisons are 1 vs 2, 4 vs 2, 4 vs 3, 4 vs 8, 7 vs 8, 9 vs 8 and 9 vs 10; at that point the first run is empty, so the remaining 10 is output without a comparison. That is 7 comparisons, the maximum m + n − 1 = 7 for merging runs of lengths m and n. A merge looks at each element of the sorted runs only once, so it takes O(m + n), and since merge sort repeats this over log₂ n levels, the whole sort takes O(n log n).

  • A. It is not enough to compare only as many times as one run's length. The values alternate between the runs, so more comparisons are needed.
  • B. Correct. Only the last value, 10, is output without a comparison, so there are 7 comparisons.
  • C. The last element has nothing left to be compared with, so the count is not 8.
Practice this topic Back to topic

Related calculators

Books on Data Structures and Algorithms Ad

As an Amazon Associate I earn from qualifying purchases.

More Data Structures and Algorithms questions

  1. A binary heap is stored in an array a[0], a[1], a[2], … with the root at a[0], filling each level from left to right starting at the top. Which are the children and the parent of a[4]?
  2. A max-heap, in which each parent's value is at least as large as its children's, is stored in an array with the root at a[0]. 45 is added to the heap 50, 30, 40, 10, 20, 35 by placing it at the end and then swapping it with its parent as long as it is larger than the parent. What is the resulting array?
  3. When a binary search tree is traversed in in-order (visiting the left subtree, then the node, then the right subtree), how are the values of the visited nodes ordered? Assume all values are distinct.
  4. The values 50, 30, 70, 20, 40, 60, 80 are inserted in this order into an empty binary search tree. In what order are the nodes visited when the tree is traversed in post-order (left subtree, right subtree, then the node)?
  5. The values 1, 2, 3, …, 1000 are inserted in this order into an empty binary search tree (no rebalancing is done). When searching this tree for 1000, how many nodes are compared, starting from the root, before it is found?