Lecture 5 Merge Sort
Lecture 5 Merge Sort
Aimal Rextin
NUST-SEECS
February 7, 2025
Merge sort -Conceptual Level
Dividing an Array
p q r
Merge-Sort Algorithm
Algorithm 1 Merge-Sort(A, p, r)
1: if p < r then
2: q = ⌊(p + r )/2⌋
3: Merge-Sort(A, p, q)
4: Merge-Sort(A, q + 1, r )
5: Merge(A, p, q, r )
6: end if
Merge Procedure (Part 1)
Algorithm 2 Merge(A, p, q, r)
1: n1 = q − p + 1
2: n2 = r − q
3: Let L[1 . . . n1 + 1] and R[1 . . . n2 + 1] be new arrays
4: for i = 1 to n1 do
5: L[i] = A[p + i − 1]
6: end for
7: for j = 1 to n2 do
8: R[j] = A[q + j]
9: end for
10: L[n1 + 1] = ∞
11: R[n2 + 1] = ∞
f (n) = 0
or tell that such a number n does not exist. The basic operation in
your algorithm is querying if f (i) is positive or negative or zero.
Each operation has a unit cost.
Hint: Be careful! The search space is infinite here.
Solution
Solution
Solution
▶ Now we can apply binary search from low to high to find the
n such that f (n) = 0.