Exercise 2.3-2

Rewrite the MERGE procedure so that it does not use sentinels, instead stopping once either array \(L\) or \(R\) has had all its elements copied back to \(A\) and then copying the remainder of the other array back into \(A\).

MERGE-SORT (A, p, q, r)

01 n₁ = q - p + 1

02 n₂ = r - q

03 Let L[1 . . n₁] and R[1 . . n₂] be new arrays

04 for i = 1 to n₁

05      L[i] = A[p + i - 1]

06 for j = 1 to n₂

07      R[j] = A[q + j]

08 i = 1

09 j = 1

10 for k = p to r

11      if j > n₂

12          A[k] = L[i]

13          i = i + 1

14      else if if i > n₁

15          A[k] = R[j]

16          j = j + 1

17      else if L[i] ≤ R[j]

18          A[k] = L[i]

19          i = i + 1

20      else

21          A[k] = R[j]

22          j = j + 1