Lec 5
Lec 5
Lecture 5: August 12
Instructor: Prof. Prateek Vishnoi Indian Institute of Technology, Mandi
First Approach
Analysis
Since best sorting algorithm that is known today is O(n log n), thus copying the arrays and sorting would
require O(n) + O(n log n) = O(n log n). Again the most famous question comes
Can we do better ??
Second thought
Compare the first element of both the arrays and place the minimum in the third array. Move towards the
next element of the copied array. Repeat the process until one of the array is exhausted. After that copy the
second remaining array in the third one.
Recurrence Relation
T (n, n) = T (n − 1, n) + c
OR
T (n, n) = T (n, n − 1) + c
T (0, n) = nc
T (n, 0) = nc
5-1
5-2 Lecture 5: August 12
Pseudo code
Recurrence Tree
T (n, n)
T (n − 1, n) T (n, n − 1) −−−−−−−−−−−−−−− c
T (n − 2, n) T (n − 1, n − 1) T (n − 1, n − 1) T (n, n − 2) −−−−−−−−−− c
According to recurrence relation, only one of the path from root to leaf will be followed. It can be easily
checked that the height of the recurrence tree is O(n) and when combined with termination step it results
in O(n)
Now we will move forward to the merge sort algorithm which is our first O(n log n) time complexity algorithm.
Merge Sort is a classic divide-and-conquer algorithm used to sort an array or list. The basic idea behind
merge sort is to divide the array into two smaller subarrays until each subarray contains a single element,
and then merge those subarrays in a way that results in a sorted array.
Pseudo code
Example
Let an unsorted array A = [11,31,25,8,37,17,40,49]. We now show the different steps of merge sort on the
following input with the help of a diagram.
5-4 Lecture 5: August 12
Recurrence Relation
(
2T ( n2 ) + cn if n > 1
T (n) =
c if n = 1
Space Complexity
Since we are using an extra array in merging the sorted arrays and some constant variables, thus
Judgment Question
Will it result in better time complexity asymptotically, if we divide the array in three equal parts instead of
two? Why or Why not?
Discussed in class.
Discussed in class.
Let A[1 . . . n] be an array of n distinct integers. If i < j and A[i] > A[j] then the pair (i,j) is called
an inversion of A. Give an algorithm that determines the number of inversions in a permutation of n
elements in O(n log n) time in worst case scenario. Do the complete analysis.