Merge Sort
Aimal Rextin
NUST-SEECS
February 7, 2025
Merge sort -Conceptual Level
Dividing an Array
▶ We cannot just divide an array
Dividing an Array
▶ We cannot just divide an array
Dividing an Array
▶ We cannot just divide an array
▶ we instead use flags pointers (basically ints) to logically divide
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] = ∞
Next: Merge the arrays back into A.
Merge Procedure (Part 2)
Algorithm 3 Merge(A, p, q, r) (continued)
1: i = 1
2: j = 1
3: for k = p to r do
4: if L[i] ≤ R[j] then
5: A[k] = L[i]
6: i =i +1
7: else
8: A[k] = R[j]
9: j =j +1
10: end if
11: end for
Now: Merge step is complete! The sorted array is updated in A.
The working
▶ Merge sort function just divides recurseively.
▶ merge function does all the work
Merge Working
Merge Working
Merge Working
Merge Working
Running time
▶ Once instance of mergesort function alone just divides the
array into two
Running time
▶ Once instance of mergesort function alone just divides the
array into two
▶ How much time does time does one instance of merge
function take?
Running time
▶ Once instance of mergesort function alone just divides the
array into two
▶ How much time does time does one instance of merge
function take?
▶ Θ(r − p − 1) or ∝ the number of elements in the array
Assignment 1 CLO 1- Marks 5-Time 8 mins
Let f : N → Z be a function defined on the set of positive integers.
We are given that f is monotonic; that is,
f (i) < f (i + 1) for all i.
Furthermore, we are also told that f (1) is negative. You have to
devise an efficient algorithm that finds an integer n such that
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
▶ We would like apply binary search but problem is we dont
know the upper limit
▶ So we first find the range to search
Solution
▶ Now we can apply binary search from low to high to find the
n such that f (n) = 0.