Professional Documents
Culture Documents
Book:, By:: Introduction To Algorithms
Book:, By:: Introduction To Algorithms
Thomas H. Cormen
Charles E. Leiserson
Ronald L. Rivest
Clifford Stein
Shashank Dwivedi 1
Lecture Contents (objectives)
Algorithm Definition
Insertion sort
Analysis of insertion sort
Example of insertion sort
(Best, Worst and Average) case analysis
Merge sort
The divide-and-conquer approach
Analyzing merge sort
Example of merge sort
Recursion tree
Average-case: (sometimes)
• T(n) = expected time of algorithm over all inputs
of size n.
Best-case:
• T(n) = minimum time of algorithm ((fastest
time to complete, with optimal inputs chosen)
(lower bound on the running time))
Computer Sciences Department 12
Worst-case and average-case analysis
6 5 3 1 8 7 2 4
1 i j n
A:
Computer Sciences Department
sorted
17 key Length[A]=n
Analyzing algorithms
Best case
Worst case
Computer Sciences Department 20
Analysis of insertion sort (cont’d)
a b
c =an2+bn-c
Computer Sciences Department 22
Example of insertion sort
8 1 4 9 3 7
MERGE-SORT A[1 . . n]
1. If n = 1, done.
2. Recursively sort A[ 1 . . n/2 ]
and A[ n/2+1 . . n ] .
3. “Merge” the 2 sorted lists.
1 2
1 2
1 2 7
1 2 7
1 2 7 9
1 2 7 9
1 2 7 9 11
1 2 7 9 11
1 2 7 9 11 12
1 2 7 9 11 12
Time = Q(n) to merge a total of n elements (linear
time).
Q(1)
Q(1)
Q(1)
Q(1)
…
Q(1)
…
Q(1) #leaves = n Q(n)
…
Q(1) #leaves = n Q(n)
Total = Q(n lg n)
Computer Sciences Department 66
Conclusions
• Q(n lg n) grows more slowly than Q(n2).