1. Gyanastra
  2. Algorithms
  3. Merge Sort and Quick Sort
  4. Merging Procedure
Free lesson, no account needed 9 min read 14 practice questions after it
Asked in past papers10 times
  • GATE CSE202620142006200519991995
  • ISRO20182015
  • UGC NET20172013

Algorithms · Merge Sort and Quick Sort

Merging Procedure

Overview

Merging takes an array AA in which two adjacent parts are already sorted — part 1 from index PP to QQ, and part 2 from index Q+1Q+1 to RR — and combines them into a single sorted list containing all the elements.
It is the combining step of Merge Sort, and it runs in time linear in the total number of elements.

Key concepts

  • Merging: given array AA where PP to QQ is sorted and Q+1Q+1 to RR is sorted, combine both parts into one sorted list containing all the elements.
    For example, an array may hold one sorted part from index 1 to 4 and another sorted part from index 5 to 8; the result must again be a sorted list containing all the elements.
  • Out-of-place procedure: merging copies all elements out of their places into new lists, and then writes them back into the original array.
  • Infinity sentinel: at the end of every list a value of infinity is written — practically a very large number, whatever is possible by the data structure used to hold the numbers.
  • Why infinity is added at the end: it ensures that if one list gets exhausted, the other list is automatically copied into AA without any modification to the code.
    Without infinity, the code would have to check whether one list is over and then copy the remaining list completely. It is only there to simplify matters.
  • Extra slot: the extra "+1" space in each list is reserved so that the infinities can be placed at the end.

How it works

  1. Create a new list LL whose size is exactly the number of elements from PP to QQ plus 1 (Q−P+1Q - P + 1 elements, plus one extra slot).
  2. Create a second list RR whose size is exactly the number of elements from Q+1Q+1 to RR plus 1 (R−QR - Q elements, plus one extra slot).
  3. Copy the first sorted list into LL and the second sorted list into RR.
  4. At the end of every list, write infinity.
  5. Write everything back into the original array AA (overwriting it), using three pointers:
    • i — the element being examined in the left list LL
    • j — the element being examined in the right list RR
    • k — the position in array AA that has to be filled
  6. Compare L[i]L[i] and R[j]R[j]; whichever is smaller is written into A[k]A[k], and that pointer (ii or jj) is incremented. kk is incremented at every step.
  7. Repeat until all elements are written; when infinity is compared with the remaining element of the other list, the remaining elements get copied and the procedure stops.

Pseudocode:

MERGE(A, P, Q, R)
    n1 = Q - P + 1          // number of elements in first list
    n2 = R - Q              // number of elements in second list
    create L of size n1 + 1
    create R of size n2 + 1
    for loop: copy A[P..Q] into L
    for loop: copy A[Q+1..R] into R
    L[n1 + 1] = infinity
    R[n2 + 1] = infinity
    i = 1, j = 1
    for K = P to R
        if L[i] <= R[j]
            A[K] = L[i]
            i = i + 1
        else
            A[K] = R[j]
            j = j + 1
        // K is incremented at every step

Formulas

  • n1=Q−P+1n_1 = Q - P + 1 — number of elements in the first list
  • n2=R−Qn_2 = R - Q — number of elements in the second list
  • Size of list L=n1+1L = n_1 + 1 (one extra slot for infinity)
  • Size of list R=n2+1R = n_2 + 1 (one extra slot for infinity)
  • If one list has size NN and the other size MM, size of the final merged list =N+M= N + M
  • Time complexity of merging two lists of sizes NN and MM =Θ(N+M)= \Theta(N + M)
  • Space complexity of merging =Θ(N+M)= \Theta(N + M) extra space

Worked examples

Example 1 Array AA with indices 1 to 8: 1,5,7,8∣2,4,6,91, 5, 7, 8 \mid 2, 4, 6, 9. Indices 1–4 are sorted and indices 5–8 are sorted.

  1. Copy first list into LL (size 4+1=54 + 1 = 5): L=1,5,7,8,∞L = 1, 5, 7, 8, \infty
  2. Copy second list into RR (size 4+1=54 + 1 = 5): R=2,4,6,9,∞R = 2, 4, 6, 9, \infty
  3. ii points to L[1]=1L[1] = 1, jj points to R[1]=2R[1] = 2, kk points to A[1]A[1].
ComparisonSmallerWritten into A[k]Pointer incremented
1 vs 21A[1] = 1i
5 vs 22A[2] = 2j
5 vs 44A[3] = 4j
5 vs 65A[4] = 5i
7 vs 66A[5] = 6j
7 vs 97A[6] = 7i
8 vs 98A[7] = 8i
∞ vs 99A[8] = 9stop

Final array AA: 1,2,4,5,6,7,8,91, 2, 4, 5, 6, 7, 8, 9 — sorted.

Example 2 (why infinity is needed) Array AA: 10,20,30,40∣1,5,6,910, 20, 30, 40 \mid 1, 5, 6, 9. PP = beginning of first sorted list, QQ = end of first sorted list, Q+1Q+1 = beginning of second sorted list, RR = end of second sorted list.

  1. LL (size 5) =10,20,30,40,∞= 10, 20, 30, 40, \infty
  2. RR (size 5) =1,5,6,9,∞= 1, 5, 6, 9, \infty
  3. ii points to L[1]=10L[1] = 10, jj points to R[1]=1R[1] = 1, kk points to A[1]A[1].
ComparisonSmallerWritten into A[k]Pointer incremented
10 vs 11A[1] = 1j
10 vs 55A[2] = 5j
10 vs 66A[3] = 6j
10 vs 99A[4] = 9j
10 vs ∞10A[5] = 10i
20 vs ∞20A[6] = 20i
30 vs ∞30A[7] = 30i
40 vs ∞40A[8] = 40i

One entire list (RR) got copied first; the other list (LL) was still left. Because of infinity at the end of RR, the remaining elements 10,20,30,4010, 20, 30, 40 are automatically copied by comparing with infinity — no special check needed in the code.

Comparison

AspectWith extra spaceWithout extra space
Time complexityΘ(n)\Theta(n)May increase
Space complexityΘ(n)\Theta(n) extra—
FeasibilityMerge method worksMerge method might not work; some other sorting method may be needed

Revision summary

  • LL has size (Q−P+1)+1(Q - P + 1) + 1 and RR has size (R−Q)+1(R - Q) + 1; the extra slot holds infinity.
  • Copying the elements into the two lists takes Θ(n)\Theta(n) time.
  • For nn elements there are nn comparisons and nn copies (each element, after being compared, is written down), so writing back takes Θ(n)\Theta(n).
  • Total time complexity of merge =Θ(n)= \Theta(n); space complexity =Θ(n)= \Theta(n).
  • For two sorted lists of sizes NN and MM: final list size =N+M= N + M, time =Θ(N+M)= \Theta(N + M) comparisons and movements, extra space needed =N+M= N + M.
  • Merge is an out-of-place procedure because elements are copied out of their places into auxiliary lists and then merged back into the array.
  • Merge needs Θ(n)\Theta(n) extra space for nn input numbers; with that extra space the merge takes Θ(n)\Theta(n) time (in-place merging without extra space is possible but more complex or slower).
  • Shortcut: put infinity (a very large value) at the end of both lists so that when one list is exhausted, the other is copied automatically without an "is list over?" check — e.g., in Example 2, after RR is exhausted, 10,20,30,4010, 20, 30, 40 are copied by comparing each with ∞\infty.

Previous-year exam insights

  • Worst-case number of comparisons to merge two sorted lists of sizes m and n is m+n-1; best case is min(m,n).
    Asked inISRO 2018UGC NET 2013GATE 1995
  • Merging k sorted lists of total size n pairwise (two at a time) optimally uses a Huffman-style strategy: repeatedly merge the two smallest lists; total cost equals the weighted external path length.
    Asked inGATE 2014GATE 1999
  • Merging k sorted lists each of size n/k using a min-heap takes Θ(nlog⁡k)\Theta(n \log k) time. Asked inGATE 2005
  • In the standard merge loop, after termination exactly one of the two arrays is exhausted; the remaining elements of the other array must be copied, so the total number of elements written is n+m and the loop runs while both i<n and j<m.
    Asked inGATE 2006
  • Merge sort's total number of merge operations on n elements is n-1 (one per internal node of the merge tree); a merge is 'void' if the last element of the left part is ≤ the first element of the right part, i.e., no interleaving occurs.
    Asked inGATE 2026
  • Straight two-way merge sort on n elements: pass 1 merges runs of size 1 into runs of size 2, pass 2 into runs of size 4, and so on; after the k-th pass, blocks of size 2k2^{k} are sorted.
    Asked inISRO 2015
Pages 1–2 of 2