Section 3 - Algorithms
Section 3 - Algorithms
Think.
Pair.
Share.
● How should we compare algorithms?
● When are structs useful?
● What is recursion?
0 1 2 3 4 5 6
Linear Search
0
1
2
0 1 2 3 4 5 6
Binary Search
3
1
0
Running Time
Linear Search Binary Search
Number of
Steps
Linear Search Binary Search
Number of
Steps
3 steps
Linear Search Binary Search
Number of
Steps
3 steps 3 steps
For any input, what is the
most number of steps my
algorithm will ever take?
How many steps will my
algorithm take for the
very worst case input?
Linear Search Binary Search
Upper Bound
Linear Search Binary Search
time to solve
log2 n
size of problem
O(n) O(n)
time to solve
O(log n)
size of problem
O(n)
time to solve
O(log n)
size of problem
Linear Search Binary Search
Upper Bound
Selection Sort
Lower Bound
Selection Sort
votes 2 1 3
candidates[0];
name Alice Bob Charlie
votes 2 1 3
candidates[0].name;
name Alice Bob Charlie
votes 2 1 3
candidates[0].votes;
Recursion
Factorial
1! = 1
Factorial
1! = 1
2! = 2 * 1
Factorial
1! = 1
2! = 2 * 1
3! = 3 * 2 * 1
Factorial
1! = 1
2! = 2 * 1
3! = 3 * 2 * 1
4! = 4 * 3 * 2 * 1
Factorial
1! = 1
2! = 2 * 1
3! = 3 * 2 * 1
4! = 4 * 3 * 2 * 1
Factorial
4! = ?
Factorial
4! = 4 * 3!
Factorial
4! = 4 * 3!
"Recursive call"
Factorial
4! = 4 * 3!
3! = 3 * …
Factorial
4! = 4 * 3!
3! = 3 * 2!
Factorial
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
Factorial
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
1! = 1
Factorial
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
1! = 1
"Base case"
Factorial
4! = 4 * 3!
3! = 3 * 2!
"Call stack"
2! = 2 * 1!
1! = 1
Factorial
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1
Factorial
4! = 4 * 3!
3! = 3 * 2 * 1
Factorial
4! = 4 * 3 * 2 * 1
Factorial
4! = 24
Factorial Exercise