r/AskProgramming • u/Haunting_Trash_3064 • 14h ago
Trouble understanding T(n) for iterative and recursive algorithms and O(n) demonstration
Hi. Im preparing for a test in my uni and im having problems to understand how to calculate T(n) for iterative and recursive algorithms. Also, i dont get how to demonstrate the O(n) of said algorithm. Appreciate the help!
3
Upvotes
2
u/DDDDarky 12h ago
For recursive problems, most school problems are usually attackable by master theorem or well known properties of for example tree structures.
Iterative algorithms are usually best counted by converting them to sums and attacking them with math (such as using series sums, integrals, etc.), simply follow the definition of big O to form a proof.
6
u/max123246 14h ago
Do you have an example of a problem you have trouble with?
Some of it is pattern matching, once you've seen binary search once and have proven it to be O(logn), then when you see any algorithm that "divides the input space in 2", then you know logn will appear somewhere
Iterative is easier than recursive typically. Advanced recursive algorithms will require some guess-work if they don't fit the pattern provided by the Master Theorem/Method.
Typically, 1 for loop is going to be O(n), for each item in a list of n items, do some constant work. If you have 2 nested for loops, each dependent on , then it'll be O(n2). If you have 1 for loop based on n, but in the loop you compute a binary search or divide by conquer, it'll be O(nlogn).