# Lecture 7 --- Order Notation & Basic Recursion - Algorithm Analysis, Formal Definition of Order Notation - Simple recursion, Visualization of recursion, Iteration vs. Recursion - “Rules” for writing recursive functions, Lots of examples ## 7.1 Algorithm Analysis Why should we bother? - We want to do better than just implementing and testing every idea we have. - We want to know why one algorithm is better than another. - We want to know the best we can do. (This is often quite hard.) How do we do it? There are several options, including: - Don’t do any analysis; just use the first algorithm you can think of that works. - Implement and time algorithms to choose the best. - Analyze algorithms by counting operations while assigning different weights to different types of operations based on how long each takes. - Analyze algorithms by assuming each operation requires the same amount of time. Count the total number of operations, and then multiply this count by the average cost of an operation. ## 7.2 Exercise: Counting Example - Suppose arr is an array of n doubles. Here is a simple fragment of code to sum of the values in the array: ```cpp double sum = 0; for (int i=0; i& v, unsigned int i) { if (i < v.size()) { cout << i << ": " << v[i] << endl; print_vec(v, i+1); } } ``` ```cpp void print_vec(std::vector& v) { print_vec(v, 0); } ``` What will this print when called in the following code? ```cpp int main() { std::vector a; a.push_back(3); a.push_back(5); a.push_back(11); a.push_back(17); print_vec(a); } ``` How can you change the second print vec function as little as possible so that this code prints the contents of the vector in reverse order?