Lecture 9 - Recursion Flashcards
What is an algorithm?
An algorithm is a step-by-step procedure for solving a stated problem.
Formal examples of pseudocode use multiplications table or binary multiplication (in computer hardware) or a less formal ways which are still understandable/non-ambiguous.
What are the principles of algorithms?
- Every recursive call must simplify the computation in some way.
- There must be special cases to handle the most simple computations directly.
Examples of algortihms in a computer context.
Dating apps, Kidney exchange
What is the difference between algorithms and programs?
Algorithms:
- performed by humans or machines
- expressed in any suitable language
- abstract (undetailed) as we like
Programs:
- performed by machines
- expressed in a programming language
- detailed and specific
What is complexity analysis?
Knowing how much effort is involved in executing an algorithm, independently from the machine, the
language and the compiler.
Eg., shopping example on goes to and from shop for each item, another goes to the shop once for all 3 items.
The first option takes more effort (6n) than the second option (2n)
What is complexity analysis useful for?
– evaluating the variations of execution time with regard to the input data
– comparing algorithms
Convert this to a program:
To compute bn: 1. Set p to 1, set q to b, and set m to n 2. While m>0 repeat: If m is odd, multiply p by q Halve m (discarding remainder) Multiply q by iteslf 3. Terminate, yielding p
public static int power2(int b, int n){ int p=1; int q=b; int m=n; while(m>0){ if((m%2) == 1) p=p*q; m=m/2; q=q*q; } return p; }
What is log2n?
It means “log to the base 2 of n”.
Eg., How many times do we need to multiply 2 by itself to get n.
Example, log16 is 4.
If n isn’t a nice power of 2 we can estimate
e.g. log210 is somewhere between 3 and 4
What is the important difference between n and log2n?
log2n grows much slower than n
or
n grows much fastser than log2n
If we define “effort” to be numbers of multiplications, as n grows
Algorithm 2 requires less effort than algorithm 1
What is an exponential function?
Look at slide 19
A growth rate that is growing much faster than all others (2^n)
Log n is way slower below the linear line. We want to try and get as close to log n as possible & stay away from the exponential function (2^n)
What are the principles of recursion that it needs to work?
- Every recursive call must simplify the computation in some way.
The method will call itself.
2.Need a stopping case (simplest input, not necessarily unique)
Must explain how to handle this case
What is a really basic example of recussion?
how many ancestors do I have? #ancestors(me) = #ancestors(mum) + #ancestors(dad) +2
Compute the area of a triangle of width and height n
Assume each [ ] square has area 1
Also called the nth triangle number
The third triangle number is 6
[ ]
[ ][ ]
[ ][ ][ ]
To compute T(n):
- Set p to 1.
- For i = 1, …, n, add i to p
- Terminate, yielding p
public static int triangle(int n){ int p=0; for(int i=1; i<=n; i++) p+=i; return p; } But what we notice is that [] // triangle width = 1 [][] // row of 2 squares
[] triangle width = 2
[][]
[][][] row of 3 squares
Based on this, know that:
triangle width = n-1
row of squares = n
We can use this information to write a recurrsive algorithm:
To compute T(n):
- If n=1, set p to 1.
- Else set p to n + T(n-1)
- Terminate, yielding p
And we can actually use this for any size of triangle eg., T(6)=6+T(5) T(5)=5+T(4) T(4)=4+T(3) T(3)=3+T(2) T(2)=2+T(1) 1 (stopping case)
So 6+5+4+3+2+1=21 returned
What is the recurssion example to compute T(n): 1. If n=1, set p to 1. 2. Else set p to n + T(n-1) 3. Terminate, yielding p in Java?
public static int triangle2(int n){
if(n==1) return 1;
return n + triangle2(n-1); //n + what we get if we calculate the same method for a smaller number
return 1 is the stopping case
triangle2(n-1) the method calls itself
What is a better formula for calcuating T(n)?
** will use it all the time in ADSIT!
Another ways of calculating T(n) using a mathematical formula:
T(n) = 1 + 2 + … + n
= n x (n+1)/2
ALWAYS look for even numbers first to make the calculation more simple: ie. 1,2,3,4,5,6,7,8,9,10 1/2*10*11=55 cancel the 2 and 10 1*5*11=55
What is a factorial function?
**Add the example
A factorial function because it keeps calling itself so many times that we end up with loads of copies.
What do permutations demonstrate?
Shows that recursive code can be more compact
What does binary search demonstrate?
Shows how recursive methods can be much more efficient
What does this mean
public static boolean allDifferent(int… args) {
Inputs an array args and the input depends on the number of integers input
Useful if we want multiple integers
Eg., if put in 0,1,2,3 it would create an array of size 4.
What is the recursive algorithm for any length of String?
To compute a list of all permutations of string s = s[0]s[1]…s[n-1]
- Create empty list L
- If n=1 add s[0] to L and yield L
- for i = 0 to n-1
- create string shortString by omitting s[i] from s
- Create list shortL=permutations(shortString)
- Add to L all strings consisting of s[i] + element of shortL
- Yield L
What is charAt() used for?
It will return the char at that index
What does .substring() do? Give an example?
Returns a string at the beginning index and ending index (-1) of a String
“hamburger”.substring(4, 8) returns “urge”
What does public String substring(int beginIndex) do?
Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
Eg., “unhappy”.substring(2) returns “happy”
What is the main drawback with recursive functions?
Efficency because eventually java will run out of size & there would be a stack overflow.
Factorial and Permutations algorithms are exponential - so your program will struggle to cope once numbers/length of string is around 10-15
Give an example of an array algorithm that uses recursion?
A binary search algorithm is used to find the position of a specific value contained in a SORTED array.
Can anything recursive be implemented iteratively (ie. without recursion)?
Yes
Sometimes you want to implement an iterative solution or a recursive process?
** a common interview question is to decide whether a problem should be implemented iteratively or recursively.
What does recursion mean?
This simply means a program calls itself typically until some final point is reached.