Algorithm Complexity Analysis


Algorithm Complexity Analysis

Anna
Today we're connecting algorithm analysis to searching and sorting. The central question is: as the input gets larger, how does the cost of an algorithm grow? We've already seen constant, logarithmic, linear, quadratic, and exponential behavior, and now we'll add log-linear behavior, especially through merge sort.

Hope
Let's begin with searching. A search algorithm finds an item, or a group of items, in a collection. That collection can be implicit, such as all the possible numbers in a range when we're finding a square root, or explicit, such as a list of student records.

Anna
Exactly. Exhaustive enumeration, bisection search, and Newton-Raphson can all be viewed as searches over an implicit collection. Here, though, we'll focus on searching an explicit list, using lists of numbers as the example.

Hope
The simplest method is linear search, sometimes called brute-force search or exhaustive enumeration. We walk through the list one item at a time, comparing each item with the value we're looking for. If we find it, we can return true; if we reach the end without finding it, we return false.

Anna
The list does not need to be sorted for linear search. Its worst-case running time is order n, where n is the list's length, because the item might be absent and we may have to inspect every element. The loop runs n times, and each iteration does constant work, so order n times order 1 is still order n.

Hope
Returning immediately when the item is found can improve the average case, because successful searches may stop early. But it does not improve the worst case: if the item is at the end, or not present at all, we still inspect the whole list.

Anna
If the list is sorted, linear search can stop early in one additional situation. As soon as we encounter an element larger than the target, we know the target cannot appear later, because all later elements are at least as large. That can improve practical or average behavior, but the worst-case complexity remains order n.

Hope
Sorting also enables bisection search, or binary search. We inspect the middle element of the sorted list. If it is the target, we're done; if the target is larger, we keep only the upper half; if it is smaller, we keep only the lower half.

Anna
The important feature is that each step cuts the remaining problem in half. After k steps, the remaining fraction is one over two to the k. We stop when that becomes about one element, so k is log base 2 of n. Therefore binary search takes order log n time, assuming the list is already sorted.

Hope
Notice that the implementation makes only one recursive call at each stage, not two. We decide which half could contain the target and discard the other half. Also, the algorithm passes index boundaries rather than copying the list, so the work inside each step is constant.

Anna
That raises an important tradeoff: when is it worth sorting a list before searching it? For one search, sorting costs at least order n because we have to look at the elements, and then binary search costs order log n. That does not beat simply doing one linear search in a meaningful worst-case comparison.

Hope
But often a collection will be searched many times. If we sort once and then perform k binary searches, the total cost is the sorting cost plus k times log n. We compare that with k linear searches, which cost k times n. Once k is large enough, the one-time sorting expense is amortized across all the searches, and sorting followed by binary search becomes worthwhile.

Anna
So the next question is how efficiently we can sort. The first example is deliberately terrible: BOGO sort, also called monkey sort, stupid sort, slow sort, permutation sort, or shotgun sort. It repeatedly rearranges the list randomly, checking each arrangement until it happens to be sorted.

Hope
An exhaustive version would try every possible permutation. Its average behavior is order n factorial, which grows roughly like n to the n for large n. Its best case is order n, because the first arrangement might already be sorted, while its random worst case has no useful finite guarantee.

Anna
A much more sensible method is bubble sort. We move from the beginning of the list toward the end, comparing adjacent elements. Whenever the earlier element is larger, we swap the pair, so larger elements gradually bubble toward the end.

Hope
After one complete pass, the largest unsorted element is guaranteed to be at the end. After the next pass, the largest remaining unsorted element is in the next-to-last position, and so on. We repeat passes until one complete pass makes no swaps, which tells us the list is sorted.

Anna
In the worst case, bubble sort makes order n passes, and each pass can examine order n elements. Those nested loops give order n squared time. Some inputs finish sooner, but its worst-case complexity is quadratic.

Hope
Selection sort takes a different approach. On the first pass, it finds the smallest element in the entire unsorted portion and places it at the front. On the next pass, it searches everything except that first position and places the next-smallest element in position two.

Anna
The key invariant is that after i steps, the first i elements are sorted, and no element in that sorted prefix is larger than the smallest element remaining in the suffix. The base case is an empty prefix, which is automatically sorted. Each step finds the smallest suffix element and extends the correctly sorted prefix, so the property remains true.

Hope
Selection sort makes n passes through progressively shorter portions of the list: roughly n, then n minus 1, then n minus 2, and so forth. Even though the portions shrink, the total is still quadratic, order n squared. A particular implementation might swap several times while searching, or search first and swap only once; that choice does not change the complexity.

Anna
Now we reach merge sort, which uses divide and conquer. A list of zero or one elements is already sorted. For a longer list, we split it into two smaller lists, recursively sort both halves, and then merge those sorted halves.

Hope
The merge step is what makes this efficient. Look only at the first remaining element of each sorted sublist. Compare them, append the smaller one to the result, and advance in the list that supplied it. Once one sublist is empty, copy the remainder of the other sublist directly onto the result.

Anna
Because each element is copied during the merge and the two lists are scanned only once, merging lists with a total of n elements takes order n time. The number of comparisons is also linear in the number of elements involved.

Hope
The recursive splitting creates logarithmically many levels. At the top level, we do order n work to merge the two halves. At the next level, there are more sublists, but their total size is still n, so that level also does order n work. Every level costs order n, and there are order log n levels.

Anna
Therefore merge sort takes order n log n time. It is a log-linear algorithm: logarithmically many levels, with linear work across each level. This is substantially better in the worst case than the quadratic bubble and selection sorts.

Hope
The visual pattern is simple: split an eight-element list into two lists of four, then four lists of two, then eight lists of one. Those one-element lists are already sorted, and the algorithm merges them back upward, producing larger and larger sorted lists.

Anna
This explains why sorting can be practical before repeated searching. The one-time cost is order n log n, and each later binary search is order log n. For enough searches, that total is better than repeatedly paying order n for linear search. In worst-case terms, n log n is the best general sorting performance discussed here; some algorithms can have better average behavior, but the comparison is focused on worst-case performance.

Hope
So the hierarchy we have encountered places constant and logarithmic growth above linear, then log-linear, then quadratic, with exponential and factorial-style growth becoming much more expensive. When designing algorithms, we generally want behavior as high in that hierarchy as possible, meaning slower growth as the input increases.

Anna
The lecture also connects these algorithms to broader computational thinking. Data structures such as tuples, lists, dictionaries, and more complicated structures give us ways to represent knowledge. Iteration and loops provide computational patterns, while recursion breaks a problem into simpler versions of itself.

Hope
Abstraction means capturing a computation inside a procedure so we can use it without knowing every internal detail. As long as the procedure delivers its promised result, we can treat it like a reliable service. Classes and methods extend that idea by organizing data together with the operations that act on it, helping us modularize systems.

Anna
The larger goal is computational problem solving: take a problem from biology, chemistry, mathematics, physics, or engineering, turn it into an algorithm, and use a computer to execute and evaluate that process. Complexity analysis helps us ask not only whether a solution works, but also how well it will scale.

Hope
That leads to the three A's of computational thinking: abstraction, automation, and algorithms. First, identify the right abstraction and decompose the problem. Second, automate or mechanize that abstraction as a sequence of steps. Third, express those steps clearly enough that they can be executed and communicated.

Anna
Writing an algorithm forces precision. It clarifies what the problem is, what information is needed, and how each step contributes to the solution. Recursion is especially useful when a hard problem can be divided into simpler problems of the same kind, as merge sort demonstrates.

Hope
And that is the main lesson: choose algorithms with growth rates that fit the task. Linear search is simple and works without sorting; binary search is much faster but requires sorted data; bubble sort and selection sort are straightforward quadratic methods; and merge sort uses divide and conquer to achieve order n log n sorting.

Ask anything
We've read this whole study set, so questions about it get the best answers.