On your last point: when talking about algorithms in the abstract, we still use similar structures to those used in programming; loops and branches (if/else) are the most critical in many of the common complexity analysis cases (big-O, little-O, big-Theta).
Big-O specifically refers to the worst-case time or space complexity of an algorithm. Assume that your algorithm operates on an input of n elements. Then:
- A straight iteration over every element (`for item in items: print(item)`) runs in linear time: O(n) for n elements.
- If your algorithm has a nested loop, and each of the loops has a bound which is either literally n, or derived from n, this is quadratic time (O(n^2)). For example, this naïve search for duplicates:
for item in items:
for dupe_candidate in items:
if item == dupe_candidate:
print(f"{item} is a dupe!")
This extends into higher powers (O(n^3), O(n^4), etc)) with deeper nesting of loops, and if inner loops are dependent upon other input parameters, you can use a separate variable for that (O(n^m) for example).- There are also cases where algorithms run in sub-linear time. Two very common cases for that are logarithmic time (O(log(m, n)), which often comes up in algorithms over height-balanced search trees of arity m, and constant time (O(1)), which means that regardless of the input size, the algorithm will run in the same amount of time (which sounds great, until you realize that for large enough values of 1 this is actually really slow -- so you often see these constant-time algorithms find niche applications at large scales where even a very large 1 is still small).
From a math perspective, this is really just modelling a function's behaviour over a given input range, as well as when it tends towards infinity. Understanding your algorithm's time and space complexity as well as the input domain are a very common first step towards identifying the data structures and algorithms which will make up your application.
Ah yes, I knew this in the past and you just helped me remember, thanks.
So basically, this is 2.25 nested loops!