SlideShare a Scribd company logo
1 of 49
Algorithm Design and Complexity
Course 3
Overview







Recursive Algorithms
Towers of Hanoi
Merge Sort
Complexity & Recurrence Relations (RR)
Methods of Solving RR







Iteration
Recursion trees
Substitution
Master theorem

Quick Sort
Recursive Algorithms


Recursive algorithms are algorithms that call
themselves in order to compute the solution for the
problem


They call themselves because they need to solve the
same problem for some other input data







That is usually a part of the original input data
But has a smaller size
Sub-problems

They must have a stopping condition
They use the solution of the sub-problems to compute the
solution to the main problem
Recursive Algorithms (2)



Generic recursive algorithm
It is difficult to find a generic formula to recursive
algorithms

Compute_Recursive(A[1..n])
IF (n <= 1)
// end of recursion
RETURN SIMPLE_A_SOL
Preprocess(A)
B[1..k] = Divide(A)
// smaller subproblems
FOR (i = 1.. k)
B_SOL[i] = Compute_Recursive(B[i][1..ni])
// recursion
A_SOL = Combine(B[1..k])
// combine
solutions
RETURN A_SOL
Complexity of Recursive Algorithms


Because the algorithms/procedures call themselves:






The running time shall be described by a recursive
equation

T(n) = Time_for(iterative part, n)
+ Time_for(recurse part, n)
T(n) is the running time for Compute_Recursive
Time_for means the running time for parts of the
algorithm: it depends on the size of the input data for
the current call of Compute_Recursive


they depend of n
Recurrence Relations


T(n) =
Time_for(Preprocess, n)
Time_for(Divide, n)
Time_for(Combine, n))
T(n1)
…
T(nk)

where
n1 , … nk < n

+
+
+
+
Design Technique: Divide et Impera



Step 1: Divide the problem into simpler subproblems of smaller size
Step 2: Solve the sub-problems using the same
method as for solving the main problem (Impera)


If the sub-problems are simple enough, solve them
iteratively



Step 3: Combine the solutions to the sub-problems
in order to find the solutions to the main problem



Technique adapted to algorithms from
politics, war, etc (as old as the Roman Empire)
Design Technique: Divide et Impera (2)


There are some general recurrence relations for D&I


T(n) = a * T(n / b) + C(n) + D(n)





b > 1  number of sub-problems of equal size
1 <= a ( <= b usually)  number of sub-problems that are
solved

T(n) = a * T (n - b) + C(n) + D(n)


Decrease et impera
Towers of Hanoi






http://en.wikipedia.org/wiki/Tower_of_Hanoi
Given three rods and a number of disks of different sizes
which can slide onto any rod.
All the disks are placed in a neat stack in ascending
order of size on one rod, the smallest at the top, thus
making a conical shape.
The objective of the puzzle is to move the entire stack to
another rod, obeying the following rules:





Only one disk may be moved at a time.
Each move consists of taking the upper disk from one of the
rods and sliding it onto another rod, on top of the other disks
that may already be present on that rod.
No disk may be placed on top of a smaller disk.
Towers of Hanoi (2)
Towers of Hanoi – Recursive Algorithm


Procedure for recursive solution:






label the pegs A, B, C—these labels may move at
different steps
let n be the total number of discs
number the discs from 1 (smallest, topmost) to n
(largest, bottommost)

To move n discs from peg A to peg C:





move n−1 discs from A to B. This leaves disc #n alone on
peg A
move disc #n from A to C
move n−1 discs from B to C so they sit on disc #n
Towers of Hanoi–Recursive Algorithm (2)
Hanoi(N, Src, Aux, Dst)
IF (N <= 1 )
RETURN
Hanoi(N - 1, Src, Dst, Aux)
Move from Src to Dst
Hanoi(N - 1, Aux, Src, Dst)
Iterative complexity: (1)
Recursive complexity: 2 * T(N - 1)
T(N) = 2 * T(N - 1) +

(1) Complexity??
Legend





Indian temple with 64 disks
The priests move the disks according to the rules of the
problem
The world will end when they will finish arranging the
disks on the new pillar
T(N)
T(N - 1)
…
T(2)
T(1)

= 2 * T(N - 1) +
= 2 * T(N - 2) +

T(N)

=

= 2 * T(1) +
= (1)

(1)

(1)
(1)

|*2
| * 2N-2
| * 2N-1

(1) * (1 + 2 + … + 2N-1) = 2N *

(1) =

(2N)
Conclusion




If 1 second needed to move a disk from a pillar to
another
264 seconds are needed to complete the task
Almost 16 * 1018 seconds
Merge Sort
MergeSort(A, p, r)
IF (p >= r)
// stop condition; n = r – p <= 0
RETURN;
q = floor((p+r) / 2)
// split the array in two
// (equal) halves
MergeSort(A, p, q)
// A1 - sorted
MergeSort(A, q+1, r)
// A2 - sorted
Merge(A, p, q, r)
// merge 2 sorted sub// arrays of half-size
RETURN;
Initial call: MergeSort(A, 1, n)
Merge Sort – Running Time



T(n) = Recursive Running Time + Iterative Running
Time
Recursive RT = 2 * T(n / 2)
Iterative RT
= (n) + (1) = (n)



Thus:




T(n) = 2 * T(n / 2) +


(n)

In order to compute the order of growth of recursive
algorithms, we need to know how to compute the
solution to recurrence relations!
Recurrence Relations



T(n) = T(n-1) + 1
T(n) = T(n-k) + n
T(n) = T(n/2) + 1
T(n) = 5*T(n/3) + n log n
T(n) = T(sqrt(n)) + 1
…
Stop condition: usually T(1) =



Can be solved using 4 methods:













Iteration
Recursion Trees
Substitution
Master Theorem

(1)
Recurrence Relations (2)
Technical Issues - Simplifications





Use of floors and ceilings
Compute exact vs. asymptotic solution for a recurrence
relation
Stopping / boundary conditions
The iterative and recursion trees methods are not strong
mathematical methods for using recurrences




The substitution method and Master theorem are strong
mathematical methods as they use:






Because they use partial induction

Complete induction: substitution method
A proven theorem: Master method

However, I accept any method as long as the result is
correct!
Iteration Method





Algebraic method
Simplest way to solve recurrences
May be very difficult to solve some of them
Expand the terms that are on the right side of the recurrence, by using the
same formula and the new parameter (size of the input data)
T(n)
T(n - 1)
…
T(n - k)
…
T(2) = T(n-n+2)
T(1)

Add them up:
T(n)

= T(n - 1) + n
= T(n - 2) + n - 1

= T(n - k - 1) + n - k
= T(1) + 2
=1

=1+2+…+n=

(n2)
Iteration Method (2)


Advantages:





Very simple
Can compute exact and asymptotical solutions

Disadvantages:



Not mathematically rigorous
Difficult to solve some recurrences

T(n) = T(2n/3) + T(n/3) + n
T(n) = T(n/4) + T(n/2) + 1
Iteration Method – Exercises


T(n) = 2 * T(n/2) +


(n)

Solved on whiteboard



T(n) = T(sqrt(n)) + 1
T(n) = T(sqrt(n)) + n



Sometimes, it is helpful to use substitutions:






Of variables (e.g. let n = 2k)
Of recurrences (e.g. on whiteboard)
Recursion Trees



Similar to the iteration method
Uses a graphical model for expanding the recurrent
terms that are not known
The result is a recursion tree



E.g. T(n) = T(n-1) + n



Recursion Trees (2)








For each recurrent term on the right side of the
recurrence relation, expand it into a child of the current
node
Continue this process recursively, until stopping
conditions are reached
The complexity of a node is the sum of the complexities
in the nodes that are part of the entire sub-tree
dominated by that node
=> The solution of the recurrence relation is the
complexity of the root node
=> The solution of the recurrence relation is the sum of
the complexities of each node in the tree


For simplifying the procedure, sum up on each level of the tree
in order to notice a possible pattern => incomplete induction
Recursion Trees – Exercises


T(n) = 2 * T(n/2) +




(n)

Solved on whiteboard

T(n) = T(n/3) + T(2n/3) +

(n) => T(n) =

(n logn)
Recursion Trees – Exercises (2)


T(n) = T(n/2) + T(n/4) + T(n/8) + n
Iteration Method – Exercises (3)


T(n) = T(n/2) + T(n/4) + T(n/8) + n => T(n) =

(n)
Recursion Trees – Conclusions


Advantages:





Disadvantages





Simple to solve them
Powerful, can solve a lot of interesting recurrences
Not mathematically rigorous

At least as powerful as the iteration method
Substitutions (of variables, recurrence relations) may
also prove helpful
Substitution Method



The most rigorous method for solving recurrences
It uses complete induction for proving that the
solution is correct





Can be used for exact solutions
Can be used for asymptotical solutions

However, first you need to guess the correct solution





Guess = use iteration or recursion trees to compute it
Guess = experience
Guess = bound the recurrence and solve it
Etc.
Substitution Method – Example


Used for exact solutions



1. Guess T(n) = n logn + n
2. Prove by induction
Basis
Inductive step







Inductive hypothesis




Also true for T(n/2)

Then, prove T(n)
Substitution Method – Example (2)
Substitution Method – Example (3)



Used for asymptotic bounds
In order to prove (f(n)), you need to:






Prove upper bound: O(f(n))
Prove lower bound (f(n))
Independently

Start from the definitions of O and
Substitution Method – Example (4)


Upper bound



1. Guess: T(n) = O(n logn)
2. Prove by induction for n:


Substitution Method – Example (5)


Lower bound



1. Guess: T(n) = (n logn)
2. Prove by induction for n:


Substitution Method – Exercise


T(n) = 8*T(n/2) +




(n2)

Solved on whiteboard

Remarks: I accept solutions that use n2 instead of
(n2) for the free term, as the demonstration gets
easier


The important part of the demonstration is still there
Substitution Method – Conclusions


Advantages






Mathematically rigorous
Can solve any recurrence relation
Can prove exact or asymptotic solutions

Disadvantages




Need to guess the correct solution
More difficult to use this method
Master Method


Is based on the Master theorem


Therefore, it is mathematically rigorous because the
theorem can be verified using recursion trees, plus
substitution for each case of the theorem  exercise



Can solve recurrences that have the following
generic formula:



Compare
There are three interesting cases


Master Method (2)


http://people.csail.mit.edu/thies/6.046web/master.pdf - exercises here



More exercises in CLRS – chapter 4
Some examples on whiteboard


Master Method – Conclusions


Advantages





Disadvantages






Very simple to use
Rigorous
Can only compute asymptotic solutions (though it always
offers the order of growth - )
Can only be used for special cases of the recurrence
It has holes between the three cases

In order to fill in the holes, there is an extension to
the master theorem
(http://www.math.uic.edu/~leon/cs-mcs401s08/handouts/extended_master_theorem.pdf)
Practice Makes Perfect
Quick Sort





Another divide and conquer sorting algorithm
One of the best sorting algorithms in practice
Although the worst case is O(n2)



Idea: How can I divide an array into two parts such
that, after sorting each part, there won’t be a need
for merging the resulting sorted sub-arrays?



Solution:
<= x

x
x - pivot

>= x
Quick Sort (2)






1. Divide:
Partition the array A[p..r] into two sub-arrays:
- A[p..q-1] that contains elements <= A[q]
- A[q+1..r] that contains elements >= A[q]
- A[q] = x is called the pivot
2. Impera:
Solve A[p..q-1] and A[q+1..r] recursively if they are not
simple enough
3. Combine:
Nothing to do as:
- A[p..q-1] is sorted and all elements <= A[q]
- A[q+1..r] is sorted and all elements >= A[q]
Quick Sort – Pseudocode


It is important to partition efficiently!

QuickSort(A, p, r)
IF (p >= r)
// stop condition; n = r – p <= 0
RETURN ;
q = Partition(A, p, r)
// determine the two sub-arrays
QuickSort(A, p, q-1)
// A1 - sorted
QuickSort(A, q+1, r)
// A2 - sorted
// nothing more to do 
RETURN;
Initial call: QuickSort(A, 1, n)
Quick Sort – Complexity


T(n) = Time_for(Partition, n) + T(n1) + T(n2)







n1 = size(A[p..q-1])
n2 = size(A[q+1..r])
n = size(A[p..r])
n1 + n2 = n – 1

We want a good algorithm for Partition!


At most O(n)
Quick Sort – Partition



Several methods exist for an efficient partitioning
I like the one in MIT’s Introduction to Algorithms course:

Partition(A, p, r)
x = A[p]
i=p
FOR (j = p+1 .. r)
IF (A[j] < x)
i++
SWAP(A[i], A[j])
SWAP(A[p], A[i])
RETURN i
Complexity: O(n)
Prove of correctness on the whiteboard
Quick Sort – Complexity (2)


Worst case:



n1 = 0 and n2 = n-1
n1 = n-1 and n2 = 0



T(n) = T(n-1) + T(0) + n = T(n-1) + n
=> T(n) = (n2)



Best case:









n1 = n2 = n/2 (approximately)

T(n) = 2* T(n/2) + n
=> T(n) = (n logn)
Quick Sort – Complexity (3)









Unbalanced partition
T(n) = T(k*n) + T((1-k)*n) + n
each time the same 0< k <1
Prove that:
T(n) = (n logn)

Approximation of the average case
U(n) = L(n-1) + n
at one step a bad partition
L(n) = 2*U(n/2) + n
the other step a good
partition
U(n) = L(n) = O(n logn)
Demo: on whiteboard
Randomized Partition






Choose the pivot randomly at each step
This way, you avoid with a very high probability the
worst case
The greater the array, the greater the probability to
have the complexity (n logn)
Works very well in practice!
References


CLRS – Chapters 4, 7



MIT OCW – Introduction to Algorithms – video
lectures 2-4

More Related Content

What's hot

Travelling salesman dynamic programming
Travelling salesman dynamic programmingTravelling salesman dynamic programming
Travelling salesman dynamic programmingmaharajdey
 
Regular Languages
Regular LanguagesRegular Languages
Regular Languagesparmeet834
 
Lecture: Regular Expressions and Regular Languages
Lecture: Regular Expressions and Regular LanguagesLecture: Regular Expressions and Regular Languages
Lecture: Regular Expressions and Regular LanguagesMarina Santini
 
Introduction to NP Completeness
Introduction to NP CompletenessIntroduction to NP Completeness
Introduction to NP CompletenessGene Moo Lee
 
Algorithm chapter 10
Algorithm chapter 10Algorithm chapter 10
Algorithm chapter 10chidabdu
 
P, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-HardP, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-HardAnimesh Chaturvedi
 
DESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMSDESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMSGayathri Gaayu
 
Stressen's matrix multiplication
Stressen's matrix multiplicationStressen's matrix multiplication
Stressen's matrix multiplicationKumar
 
Brute force-algorithm
Brute force-algorithmBrute force-algorithm
Brute force-algorithm9854098540
 
Recurrence relation solutions
Recurrence relation solutionsRecurrence relation solutions
Recurrence relation solutionssubhashchandra197
 
Asymptotic Notation and Complexity
Asymptotic Notation and ComplexityAsymptotic Notation and Complexity
Asymptotic Notation and ComplexityRajandeep Gill
 

What's hot (20)

Travelling salesman dynamic programming
Travelling salesman dynamic programmingTravelling salesman dynamic programming
Travelling salesman dynamic programming
 
Spanning trees
Spanning treesSpanning trees
Spanning trees
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Time complexity
Time complexityTime complexity
Time complexity
 
Regular Languages
Regular LanguagesRegular Languages
Regular Languages
 
Lecture: Regular Expressions and Regular Languages
Lecture: Regular Expressions and Regular LanguagesLecture: Regular Expressions and Regular Languages
Lecture: Regular Expressions and Regular Languages
 
Introduction to NP Completeness
Introduction to NP CompletenessIntroduction to NP Completeness
Introduction to NP Completeness
 
Daa unit 2
Daa unit 2Daa unit 2
Daa unit 2
 
Algorithm chapter 10
Algorithm chapter 10Algorithm chapter 10
Algorithm chapter 10
 
P, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-HardP, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-Hard
 
DESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMSDESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMS
 
Time complexity
Time complexityTime complexity
Time complexity
 
Stressen's matrix multiplication
Stressen's matrix multiplicationStressen's matrix multiplication
Stressen's matrix multiplication
 
Brute force-algorithm
Brute force-algorithmBrute force-algorithm
Brute force-algorithm
 
Chapter18
Chapter18Chapter18
Chapter18
 
Np complete
Np completeNp complete
Np complete
 
Recurrence relation solutions
Recurrence relation solutionsRecurrence relation solutions
Recurrence relation solutions
 
Asymptotic Notation and Complexity
Asymptotic Notation and ComplexityAsymptotic Notation and Complexity
Asymptotic Notation and Complexity
 
Shortest path algorithms
Shortest path algorithmsShortest path algorithms
Shortest path algorithms
 

Similar to Algorithm Design and Complexity - Course 3

Lecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrencesLecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrencesjayavignesh86
 
T2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptxT2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptxGadaFarhan
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquerVikas Sharma
 
Copy of y16 02-2119divide-and-conquer
Copy of y16 02-2119divide-and-conquerCopy of y16 02-2119divide-and-conquer
Copy of y16 02-2119divide-and-conquerJoepang2015
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrencesMegha V
 
Quicksort analysis
Quicksort analysisQuicksort analysis
Quicksort analysisPremjeet Roy
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquerchidabdu
 
CS330-Lectures Statistics And Probability
CS330-Lectures Statistics And ProbabilityCS330-Lectures Statistics And Probability
CS330-Lectures Statistics And Probabilitybryan111472
 
Admission in india 2015
Admission in india 2015Admission in india 2015
Admission in india 2015Edhole.com
 
RECURRENCE EQUATIONS & ANALYZING THEM
RECURRENCE EQUATIONS & ANALYZING THEMRECURRENCE EQUATIONS & ANALYZING THEM
RECURRENCE EQUATIONS & ANALYZING THEMAlpana Ingale
 
Recurrence relationclass 5
Recurrence relationclass 5Recurrence relationclass 5
Recurrence relationclass 5Kumar
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theoremRajendran
 

Similar to Algorithm Design and Complexity - Course 3 (20)

Daa chapter 2
Daa chapter 2Daa chapter 2
Daa chapter 2
 
Lecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrencesLecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrences
 
T2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptxT2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptx
 
2.pptx
2.pptx2.pptx
2.pptx
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
L2
L2L2
L2
 
Copy of y16 02-2119divide-and-conquer
Copy of y16 02-2119divide-and-conquerCopy of y16 02-2119divide-and-conquer
Copy of y16 02-2119divide-and-conquer
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrences
 
L2
L2L2
L2
 
Quicksort analysis
Quicksort analysisQuicksort analysis
Quicksort analysis
 
Recurrence relation
Recurrence relationRecurrence relation
Recurrence relation
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquer
 
numerical.ppt
numerical.pptnumerical.ppt
numerical.ppt
 
CS330-Lectures Statistics And Probability
CS330-Lectures Statistics And ProbabilityCS330-Lectures Statistics And Probability
CS330-Lectures Statistics And Probability
 
03 dc
03 dc03 dc
03 dc
 
Admission in india 2015
Admission in india 2015Admission in india 2015
Admission in india 2015
 
RECURRENCE EQUATIONS & ANALYZING THEM
RECURRENCE EQUATIONS & ANALYZING THEMRECURRENCE EQUATIONS & ANALYZING THEM
RECURRENCE EQUATIONS & ANALYZING THEM
 
Recurrence relationclass 5
Recurrence relationclass 5Recurrence relationclass 5
Recurrence relationclass 5
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theorem
 
Laplace_1.ppt
Laplace_1.pptLaplace_1.ppt
Laplace_1.ppt
 

More from Traian Rebedea

An Evolution of Deep Learning Models for AI2 Reasoning Challenge
An Evolution of Deep Learning Models for AI2 Reasoning ChallengeAn Evolution of Deep Learning Models for AI2 Reasoning Challenge
An Evolution of Deep Learning Models for AI2 Reasoning ChallengeTraian Rebedea
 
AI @ Wholi - Bucharest.AI Meetup #5
AI @ Wholi - Bucharest.AI Meetup #5AI @ Wholi - Bucharest.AI Meetup #5
AI @ Wholi - Bucharest.AI Meetup #5Traian Rebedea
 
Deep neural networks for matching online social networking profiles
Deep neural networks for matching online social networking profilesDeep neural networks for matching online social networking profiles
Deep neural networks for matching online social networking profilesTraian Rebedea
 
Intro to Deep Learning for Question Answering
Intro to Deep Learning for Question AnsweringIntro to Deep Learning for Question Answering
Intro to Deep Learning for Question AnsweringTraian Rebedea
 
How useful are semantic links for the detection of implicit references in csc...
How useful are semantic links for the detection of implicit references in csc...How useful are semantic links for the detection of implicit references in csc...
How useful are semantic links for the detection of implicit references in csc...Traian Rebedea
 
A focused crawler for romanian words discovery
A focused crawler for romanian words discoveryA focused crawler for romanian words discovery
A focused crawler for romanian words discoveryTraian Rebedea
 
Detecting and Describing Historical Periods in a Large Corpora
Detecting and Describing Historical Periods in a Large CorporaDetecting and Describing Historical Periods in a Large Corpora
Detecting and Describing Historical Periods in a Large CorporaTraian Rebedea
 
Practical machine learning - Part 1
Practical machine learning - Part 1Practical machine learning - Part 1
Practical machine learning - Part 1Traian Rebedea
 
Propunere de dezvoltare a carierei universitare
Propunere de dezvoltare a carierei universitarePropunere de dezvoltare a carierei universitare
Propunere de dezvoltare a carierei universitareTraian Rebedea
 
Automatic plagiarism detection system for specialized corpora
Automatic plagiarism detection system for specialized corporaAutomatic plagiarism detection system for specialized corpora
Automatic plagiarism detection system for specialized corporaTraian Rebedea
 
Relevance based ranking of video comments on YouTube
Relevance based ranking of video comments on YouTubeRelevance based ranking of video comments on YouTube
Relevance based ranking of video comments on YouTubeTraian Rebedea
 
Opinion mining for social media and news items in Romanian
Opinion mining for social media and news items in RomanianOpinion mining for social media and news items in Romanian
Opinion mining for social media and news items in RomanianTraian Rebedea
 
PhD Defense: Computer-Based Support and Feedback for Collaborative Chat Conve...
PhD Defense: Computer-Based Support and Feedback for Collaborative Chat Conve...PhD Defense: Computer-Based Support and Feedback for Collaborative Chat Conve...
PhD Defense: Computer-Based Support and Feedback for Collaborative Chat Conve...Traian Rebedea
 
Importanța algoritmilor pentru problemele de la interviuri
Importanța algoritmilor pentru problemele de la interviuriImportanța algoritmilor pentru problemele de la interviuri
Importanța algoritmilor pentru problemele de la interviuriTraian Rebedea
 
Web services for supporting the interactions of learners in the social web - ...
Web services for supporting the interactions of learners in the social web - ...Web services for supporting the interactions of learners in the social web - ...
Web services for supporting the interactions of learners in the social web - ...Traian Rebedea
 
Automatic assessment of collaborative chat conversations with PolyCAFe - EC-T...
Automatic assessment of collaborative chat conversations with PolyCAFe - EC-T...Automatic assessment of collaborative chat conversations with PolyCAFe - EC-T...
Automatic assessment of collaborative chat conversations with PolyCAFe - EC-T...Traian Rebedea
 
Conclusions and Recommendations of the Romanian ICT RTD Survey
Conclusions and Recommendations of the Romanian ICT RTD SurveyConclusions and Recommendations of the Romanian ICT RTD Survey
Conclusions and Recommendations of the Romanian ICT RTD SurveyTraian Rebedea
 
Istoria Web-ului - part 2 - tentativ How to Web 2009
Istoria Web-ului - part 2 - tentativ How to Web 2009Istoria Web-ului - part 2 - tentativ How to Web 2009
Istoria Web-ului - part 2 - tentativ How to Web 2009Traian Rebedea
 
Istoria Web-ului - part 1 (2) - tentativ How to Web 2009
Istoria Web-ului - part 1 (2) - tentativ How to Web 2009Istoria Web-ului - part 1 (2) - tentativ How to Web 2009
Istoria Web-ului - part 1 (2) - tentativ How to Web 2009Traian Rebedea
 

More from Traian Rebedea (20)

An Evolution of Deep Learning Models for AI2 Reasoning Challenge
An Evolution of Deep Learning Models for AI2 Reasoning ChallengeAn Evolution of Deep Learning Models for AI2 Reasoning Challenge
An Evolution of Deep Learning Models for AI2 Reasoning Challenge
 
AI @ Wholi - Bucharest.AI Meetup #5
AI @ Wholi - Bucharest.AI Meetup #5AI @ Wholi - Bucharest.AI Meetup #5
AI @ Wholi - Bucharest.AI Meetup #5
 
Deep neural networks for matching online social networking profiles
Deep neural networks for matching online social networking profilesDeep neural networks for matching online social networking profiles
Deep neural networks for matching online social networking profiles
 
Intro to Deep Learning for Question Answering
Intro to Deep Learning for Question AnsweringIntro to Deep Learning for Question Answering
Intro to Deep Learning for Question Answering
 
What is word2vec?
What is word2vec?What is word2vec?
What is word2vec?
 
How useful are semantic links for the detection of implicit references in csc...
How useful are semantic links for the detection of implicit references in csc...How useful are semantic links for the detection of implicit references in csc...
How useful are semantic links for the detection of implicit references in csc...
 
A focused crawler for romanian words discovery
A focused crawler for romanian words discoveryA focused crawler for romanian words discovery
A focused crawler for romanian words discovery
 
Detecting and Describing Historical Periods in a Large Corpora
Detecting and Describing Historical Periods in a Large CorporaDetecting and Describing Historical Periods in a Large Corpora
Detecting and Describing Historical Periods in a Large Corpora
 
Practical machine learning - Part 1
Practical machine learning - Part 1Practical machine learning - Part 1
Practical machine learning - Part 1
 
Propunere de dezvoltare a carierei universitare
Propunere de dezvoltare a carierei universitarePropunere de dezvoltare a carierei universitare
Propunere de dezvoltare a carierei universitare
 
Automatic plagiarism detection system for specialized corpora
Automatic plagiarism detection system for specialized corporaAutomatic plagiarism detection system for specialized corpora
Automatic plagiarism detection system for specialized corpora
 
Relevance based ranking of video comments on YouTube
Relevance based ranking of video comments on YouTubeRelevance based ranking of video comments on YouTube
Relevance based ranking of video comments on YouTube
 
Opinion mining for social media and news items in Romanian
Opinion mining for social media and news items in RomanianOpinion mining for social media and news items in Romanian
Opinion mining for social media and news items in Romanian
 
PhD Defense: Computer-Based Support and Feedback for Collaborative Chat Conve...
PhD Defense: Computer-Based Support and Feedback for Collaborative Chat Conve...PhD Defense: Computer-Based Support and Feedback for Collaborative Chat Conve...
PhD Defense: Computer-Based Support and Feedback for Collaborative Chat Conve...
 
Importanța algoritmilor pentru problemele de la interviuri
Importanța algoritmilor pentru problemele de la interviuriImportanța algoritmilor pentru problemele de la interviuri
Importanța algoritmilor pentru problemele de la interviuri
 
Web services for supporting the interactions of learners in the social web - ...
Web services for supporting the interactions of learners in the social web - ...Web services for supporting the interactions of learners in the social web - ...
Web services for supporting the interactions of learners in the social web - ...
 
Automatic assessment of collaborative chat conversations with PolyCAFe - EC-T...
Automatic assessment of collaborative chat conversations with PolyCAFe - EC-T...Automatic assessment of collaborative chat conversations with PolyCAFe - EC-T...
Automatic assessment of collaborative chat conversations with PolyCAFe - EC-T...
 
Conclusions and Recommendations of the Romanian ICT RTD Survey
Conclusions and Recommendations of the Romanian ICT RTD SurveyConclusions and Recommendations of the Romanian ICT RTD Survey
Conclusions and Recommendations of the Romanian ICT RTD Survey
 
Istoria Web-ului - part 2 - tentativ How to Web 2009
Istoria Web-ului - part 2 - tentativ How to Web 2009Istoria Web-ului - part 2 - tentativ How to Web 2009
Istoria Web-ului - part 2 - tentativ How to Web 2009
 
Istoria Web-ului - part 1 (2) - tentativ How to Web 2009
Istoria Web-ului - part 1 (2) - tentativ How to Web 2009Istoria Web-ului - part 1 (2) - tentativ How to Web 2009
Istoria Web-ului - part 1 (2) - tentativ How to Web 2009
 

Recently uploaded

How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsPooky Knightsmith
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 

Recently uploaded (20)

How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young minds
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 

Algorithm Design and Complexity - Course 3

  • 1. Algorithm Design and Complexity Course 3
  • 2. Overview      Recursive Algorithms Towers of Hanoi Merge Sort Complexity & Recurrence Relations (RR) Methods of Solving RR      Iteration Recursion trees Substitution Master theorem Quick Sort
  • 3. Recursive Algorithms  Recursive algorithms are algorithms that call themselves in order to compute the solution for the problem  They call themselves because they need to solve the same problem for some other input data      That is usually a part of the original input data But has a smaller size Sub-problems They must have a stopping condition They use the solution of the sub-problems to compute the solution to the main problem
  • 4. Recursive Algorithms (2)   Generic recursive algorithm It is difficult to find a generic formula to recursive algorithms Compute_Recursive(A[1..n]) IF (n <= 1) // end of recursion RETURN SIMPLE_A_SOL Preprocess(A) B[1..k] = Divide(A) // smaller subproblems FOR (i = 1.. k) B_SOL[i] = Compute_Recursive(B[i][1..ni]) // recursion A_SOL = Combine(B[1..k]) // combine solutions RETURN A_SOL
  • 5. Complexity of Recursive Algorithms  Because the algorithms/procedures call themselves:    The running time shall be described by a recursive equation T(n) = Time_for(iterative part, n) + Time_for(recurse part, n) T(n) is the running time for Compute_Recursive Time_for means the running time for parts of the algorithm: it depends on the size of the input data for the current call of Compute_Recursive  they depend of n
  • 6. Recurrence Relations  T(n) = Time_for(Preprocess, n) Time_for(Divide, n) Time_for(Combine, n)) T(n1) … T(nk) where n1 , … nk < n + + + +
  • 7. Design Technique: Divide et Impera   Step 1: Divide the problem into simpler subproblems of smaller size Step 2: Solve the sub-problems using the same method as for solving the main problem (Impera)  If the sub-problems are simple enough, solve them iteratively  Step 3: Combine the solutions to the sub-problems in order to find the solutions to the main problem  Technique adapted to algorithms from politics, war, etc (as old as the Roman Empire)
  • 8. Design Technique: Divide et Impera (2)  There are some general recurrence relations for D&I  T(n) = a * T(n / b) + C(n) + D(n)    b > 1  number of sub-problems of equal size 1 <= a ( <= b usually)  number of sub-problems that are solved T(n) = a * T (n - b) + C(n) + D(n)  Decrease et impera
  • 9. Towers of Hanoi     http://en.wikipedia.org/wiki/Tower_of_Hanoi Given three rods and a number of disks of different sizes which can slide onto any rod. All the disks are placed in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:    Only one disk may be moved at a time. Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod. No disk may be placed on top of a smaller disk.
  • 11. Towers of Hanoi – Recursive Algorithm  Procedure for recursive solution:     label the pegs A, B, C—these labels may move at different steps let n be the total number of discs number the discs from 1 (smallest, topmost) to n (largest, bottommost) To move n discs from peg A to peg C:    move n−1 discs from A to B. This leaves disc #n alone on peg A move disc #n from A to C move n−1 discs from B to C so they sit on disc #n
  • 12. Towers of Hanoi–Recursive Algorithm (2) Hanoi(N, Src, Aux, Dst) IF (N <= 1 ) RETURN Hanoi(N - 1, Src, Dst, Aux) Move from Src to Dst Hanoi(N - 1, Aux, Src, Dst) Iterative complexity: (1) Recursive complexity: 2 * T(N - 1) T(N) = 2 * T(N - 1) + (1) Complexity??
  • 13. Legend    Indian temple with 64 disks The priests move the disks according to the rules of the problem The world will end when they will finish arranging the disks on the new pillar T(N) T(N - 1) … T(2) T(1) = 2 * T(N - 1) + = 2 * T(N - 2) + T(N) = = 2 * T(1) + = (1) (1) (1) (1) |*2 | * 2N-2 | * 2N-1 (1) * (1 + 2 + … + 2N-1) = 2N * (1) = (2N)
  • 14. Conclusion    If 1 second needed to move a disk from a pillar to another 264 seconds are needed to complete the task Almost 16 * 1018 seconds
  • 15. Merge Sort MergeSort(A, p, r) IF (p >= r) // stop condition; n = r – p <= 0 RETURN; q = floor((p+r) / 2) // split the array in two // (equal) halves MergeSort(A, p, q) // A1 - sorted MergeSort(A, q+1, r) // A2 - sorted Merge(A, p, q, r) // merge 2 sorted sub// arrays of half-size RETURN; Initial call: MergeSort(A, 1, n)
  • 16. Merge Sort – Running Time  T(n) = Recursive Running Time + Iterative Running Time Recursive RT = 2 * T(n / 2) Iterative RT = (n) + (1) = (n)  Thus:   T(n) = 2 * T(n / 2) +  (n) In order to compute the order of growth of recursive algorithms, we need to know how to compute the solution to recurrence relations!
  • 17. Recurrence Relations  T(n) = T(n-1) + 1 T(n) = T(n-k) + n T(n) = T(n/2) + 1 T(n) = 5*T(n/3) + n log n T(n) = T(sqrt(n)) + 1 … Stop condition: usually T(1) =  Can be solved using 4 methods:           Iteration Recursion Trees Substitution Master Theorem (1)
  • 19. Technical Issues - Simplifications     Use of floors and ceilings Compute exact vs. asymptotic solution for a recurrence relation Stopping / boundary conditions The iterative and recursion trees methods are not strong mathematical methods for using recurrences   The substitution method and Master theorem are strong mathematical methods as they use:    Because they use partial induction Complete induction: substitution method A proven theorem: Master method However, I accept any method as long as the result is correct!
  • 20. Iteration Method     Algebraic method Simplest way to solve recurrences May be very difficult to solve some of them Expand the terms that are on the right side of the recurrence, by using the same formula and the new parameter (size of the input data) T(n) T(n - 1) … T(n - k) … T(2) = T(n-n+2) T(1) Add them up: T(n) = T(n - 1) + n = T(n - 2) + n - 1 = T(n - k - 1) + n - k = T(1) + 2 =1 =1+2+…+n= (n2)
  • 21. Iteration Method (2)  Advantages:    Very simple Can compute exact and asymptotical solutions Disadvantages:   Not mathematically rigorous Difficult to solve some recurrences T(n) = T(2n/3) + T(n/3) + n T(n) = T(n/4) + T(n/2) + 1
  • 22. Iteration Method – Exercises  T(n) = 2 * T(n/2) +  (n) Solved on whiteboard  T(n) = T(sqrt(n)) + 1 T(n) = T(sqrt(n)) + n  Sometimes, it is helpful to use substitutions:    Of variables (e.g. let n = 2k) Of recurrences (e.g. on whiteboard)
  • 23. Recursion Trees  Similar to the iteration method Uses a graphical model for expanding the recurrent terms that are not known The result is a recursion tree  E.g. T(n) = T(n-1) + n  
  • 24. Recursion Trees (2)      For each recurrent term on the right side of the recurrence relation, expand it into a child of the current node Continue this process recursively, until stopping conditions are reached The complexity of a node is the sum of the complexities in the nodes that are part of the entire sub-tree dominated by that node => The solution of the recurrence relation is the complexity of the root node => The solution of the recurrence relation is the sum of the complexities of each node in the tree  For simplifying the procedure, sum up on each level of the tree in order to notice a possible pattern => incomplete induction
  • 25. Recursion Trees – Exercises  T(n) = 2 * T(n/2) +   (n) Solved on whiteboard T(n) = T(n/3) + T(2n/3) + (n) => T(n) = (n logn)
  • 26. Recursion Trees – Exercises (2)  T(n) = T(n/2) + T(n/4) + T(n/8) + n
  • 27. Iteration Method – Exercises (3)  T(n) = T(n/2) + T(n/4) + T(n/8) + n => T(n) = (n)
  • 28. Recursion Trees – Conclusions  Advantages:    Disadvantages    Simple to solve them Powerful, can solve a lot of interesting recurrences Not mathematically rigorous At least as powerful as the iteration method Substitutions (of variables, recurrence relations) may also prove helpful
  • 29. Substitution Method   The most rigorous method for solving recurrences It uses complete induction for proving that the solution is correct    Can be used for exact solutions Can be used for asymptotical solutions However, first you need to guess the correct solution     Guess = use iteration or recursion trees to compute it Guess = experience Guess = bound the recurrence and solve it Etc.
  • 30. Substitution Method – Example  Used for exact solutions  1. Guess T(n) = n logn + n 2. Prove by induction Basis Inductive step     Inductive hypothesis   Also true for T(n/2) Then, prove T(n)
  • 31. Substitution Method – Example (2)
  • 32. Substitution Method – Example (3)   Used for asymptotic bounds In order to prove (f(n)), you need to:     Prove upper bound: O(f(n)) Prove lower bound (f(n)) Independently Start from the definitions of O and
  • 33. Substitution Method – Example (4)  Upper bound  1. Guess: T(n) = O(n logn) 2. Prove by induction for n: 
  • 34. Substitution Method – Example (5)  Lower bound  1. Guess: T(n) = (n logn) 2. Prove by induction for n: 
  • 35. Substitution Method – Exercise  T(n) = 8*T(n/2) +   (n2) Solved on whiteboard Remarks: I accept solutions that use n2 instead of (n2) for the free term, as the demonstration gets easier  The important part of the demonstration is still there
  • 36. Substitution Method – Conclusions  Advantages     Mathematically rigorous Can solve any recurrence relation Can prove exact or asymptotic solutions Disadvantages   Need to guess the correct solution More difficult to use this method
  • 37. Master Method  Is based on the Master theorem  Therefore, it is mathematically rigorous because the theorem can be verified using recursion trees, plus substitution for each case of the theorem  exercise  Can solve recurrences that have the following generic formula:  Compare There are three interesting cases 
  • 38. Master Method (2)  http://people.csail.mit.edu/thies/6.046web/master.pdf - exercises here  More exercises in CLRS – chapter 4 Some examples on whiteboard 
  • 39. Master Method – Conclusions  Advantages    Disadvantages     Very simple to use Rigorous Can only compute asymptotic solutions (though it always offers the order of growth - ) Can only be used for special cases of the recurrence It has holes between the three cases In order to fill in the holes, there is an extension to the master theorem (http://www.math.uic.edu/~leon/cs-mcs401s08/handouts/extended_master_theorem.pdf)
  • 41. Quick Sort    Another divide and conquer sorting algorithm One of the best sorting algorithms in practice Although the worst case is O(n2)  Idea: How can I divide an array into two parts such that, after sorting each part, there won’t be a need for merging the resulting sorted sub-arrays?  Solution: <= x x x - pivot >= x
  • 42. Quick Sort (2)    1. Divide: Partition the array A[p..r] into two sub-arrays: - A[p..q-1] that contains elements <= A[q] - A[q+1..r] that contains elements >= A[q] - A[q] = x is called the pivot 2. Impera: Solve A[p..q-1] and A[q+1..r] recursively if they are not simple enough 3. Combine: Nothing to do as: - A[p..q-1] is sorted and all elements <= A[q] - A[q+1..r] is sorted and all elements >= A[q]
  • 43. Quick Sort – Pseudocode  It is important to partition efficiently! QuickSort(A, p, r) IF (p >= r) // stop condition; n = r – p <= 0 RETURN ; q = Partition(A, p, r) // determine the two sub-arrays QuickSort(A, p, q-1) // A1 - sorted QuickSort(A, q+1, r) // A2 - sorted // nothing more to do  RETURN; Initial call: QuickSort(A, 1, n)
  • 44. Quick Sort – Complexity  T(n) = Time_for(Partition, n) + T(n1) + T(n2)      n1 = size(A[p..q-1]) n2 = size(A[q+1..r]) n = size(A[p..r]) n1 + n2 = n – 1 We want a good algorithm for Partition!  At most O(n)
  • 45. Quick Sort – Partition   Several methods exist for an efficient partitioning I like the one in MIT’s Introduction to Algorithms course: Partition(A, p, r) x = A[p] i=p FOR (j = p+1 .. r) IF (A[j] < x) i++ SWAP(A[i], A[j]) SWAP(A[p], A[i]) RETURN i Complexity: O(n) Prove of correctness on the whiteboard
  • 46. Quick Sort – Complexity (2)  Worst case:   n1 = 0 and n2 = n-1 n1 = n-1 and n2 = 0  T(n) = T(n-1) + T(0) + n = T(n-1) + n => T(n) = (n2)  Best case:     n1 = n2 = n/2 (approximately) T(n) = 2* T(n/2) + n => T(n) = (n logn)
  • 47. Quick Sort – Complexity (3)      Unbalanced partition T(n) = T(k*n) + T((1-k)*n) + n each time the same 0< k <1 Prove that: T(n) = (n logn) Approximation of the average case U(n) = L(n-1) + n at one step a bad partition L(n) = 2*U(n/2) + n the other step a good partition U(n) = L(n) = O(n logn) Demo: on whiteboard
  • 48. Randomized Partition     Choose the pivot randomly at each step This way, you avoid with a very high probability the worst case The greater the array, the greater the probability to have the complexity (n logn) Works very well in practice!
  • 49. References  CLRS – Chapters 4, 7  MIT OCW – Introduction to Algorithms – video lectures 2-4