Memory and Pointers


Memory and Pointers

Anna
Welcome back. Today is meant to feel like exposure to a few important ideas, not mastery on the spot. There’s less new syntax than usual, but these concepts—searching, efficiency, sorting, and recursion—will keep coming back throughout the semester.

Michael
Let’s begin with the picture from last time: computer memory can be thought of as a sequence of bytes, and arrays let us organize values in that memory. To a person looking at a diagram, all the values seem visible at once. A computer, by contrast, examines array elements step by step.

Anna
That difference gives us a searching problem. We have an array, and we want to know whether a particular value is in it. The output can be a Boolean: true if the value is present, false if it isn’t.

Michael
The first approach is linear search: start at one end, inspect each element in turn, and stop if you find the target. If you reach the end without finding it, report false. It’s straightforward, and it works whether or not the values are sorted.

Anna
But the order matters if we want to do better. If the array is sorted, we can inspect the middle element. If the target is smaller, search the left half; if it’s larger, search the right half. Each decision rules out about half the remaining values.

Michael
That’s binary search—the same divide-in-half idea used when searching a phone book. It can be much faster than checking every element, but it depends on a crucial condition: the data has to be sorted first.

Anna
Let’s give those speeds names. Big O notation describes an upper bound on an algorithm’s running time—often, the worst case we want to be prepared for. Linear search is O of n, because with n items it may need to inspect all n.

Michael
Binary search is O of log n, because it keeps halving the search space. Big O is an approximation: we ignore factors such as dividing by two and lower-order terms when they don’t change the overall growth for large inputs. The base of the logarithm is also omitted in this context because different bases differ only by a constant factor.

Anna
So O of n and O of n over two are treated alike: both grow proportionally to n. And log base two, log base three, or log base ten are treated alike for this purpose. The point is to compare how the running time grows as the problem gets larger.

Michael
There’s also omega notation, which describes a lower bound. It’s useful for talking about the best case. Linear search is Ω of one: if the target is the first element, it takes just one inspection.

Anna
Binary search can also be Ω of one if the target happens to be right in the middle. And some tasks have a lower bound of Ω of n. For example, to count every item accurately, you have to look at every item, even in the best case.

Michael
Best-case performance is useful to describe, but programmers often pay more attention to the upper bound, or sometimes average performance. An algorithm that’s fast only when the input happens to be especially convenient may not be dependable.

Anna
Now let’s connect the ideas to C. A small array of known numbers can be initialized with curly braces, like 4, 8, 15, 16, 23, 42. A loop can inspect each number, compare it with the target, and report success when it matches—or report failure after the loop.

Michael
That’s linear search in code. One detail: if the target isn’t found, the failure result belongs after the loop. If you printed or returned failure immediately after checking the first element, you’d never give the rest of the array a chance.

Anna
Searching names introduces a C-specific wrinkle. You can compare numbers with the equality operator, but you can’t reliably compare strings that way. A string is made up of characters, so comparing two strings means comparing their contents.

Michael
C provides the function strcmp for that. It’s declared in string.h, so that header needs to be included. For the equality test, strcmp returns zero when the strings match; a positive or negative result indicates an alphabetical ordering difference.

Anna
And when a search program finishes, its return value from main communicates success or failure to the system. In the convention shown here, zero means success and one means failure. If the program finds the name, it should finish successfully rather than continuing on to print a failure message.

Michael
That leads to a phone-book example. A phone number may look numeric, but it’s better represented as a string. It can contain dashes, parentheses, or a plus sign, and a leading zero can matter—whereas storing it as an integer could discard that zero.

Anna
One simple design uses one array of names and a second array of phone numbers. The matching name and number occupy the same index. It works, but it relies on everyone keeping those two arrays perfectly in sync.

Michael
That’s a fragile agreement. If someone sorts the names but not the numbers, or inserts an item into just one array, the associations break. C structures let us group related fields together instead.

Anna
A struct is a container for multiple data values. With typedef struct, we can define a custom type—say, person—with a name field and a number field. Then an array of people stores each person’s name and phone number together.

Michael
The dot operator accesses a field, such as people[i].name or people[i].number. This design makes the relationship between each name and number explicit, and makes it less likely that the two will get separated. It’s a pattern we’ll see again when organizing data, including in databases.

Anna
Now let’s turn from searching to sorting. Binary search is attractive, but it assumes sorted input, and sorting takes time. Whether sorting is worthwhile depends on how often you’ll search: paying to sort once can make sense if you’ll benefit from faster searches many times.

Michael
A simple sorting approach is bubble sort. Compare neighboring elements, and swap them when they’re out of order. Repeat passes through the array; large values gradually move, or ‘bubble,’ toward the right-hand end.

Anna
In the version we first described, there are roughly n passes, and each pass compares roughly n neighboring pairs. Multiplying those amounts gives a running time on the order of n squared, so bubble sort is O of n squared.

Michael
The first version also does all those passes even if the list was already sorted. That makes its best case Ω of n squared. But we can improve that: keep track of whether a pass made any swaps, and stop if it didn’t.

Anna
With that improvement, an already sorted list takes one pass of comparisons and no swaps—about n minus one comparisons. So this bubble sort version has a best-case lower bound of Ω of n, while its worst case remains O of n squared.

Michael
A different idea is selection sort. For the first position, scan the unsorted portion to find its smallest item and put that item there. Then repeat for the next position, finding the smallest item among what remains.

Anna
You can place the selected item by swapping it with whatever occupies the destination. That may move an unsorted item elsewhere, but the process will handle it later. After each pass, one more position at the front is settled.

Michael
Selection sort scans n items, then n minus one, then n minus two, and so on. Those counts add up to n times n plus one divided by two, which grows on the order of n squared. So selection sort is O of n squared.

Anna
And even if the list starts sorted, selection sort still has to scan the remaining items to know which is smallest. It doesn’t automatically recognize that the work is unnecessary, so its best-case bound is Ω of n squared too.

Michael
Comparing these algorithms visually helps: bubble sort repeatedly compares neighbors, while selection sort repeatedly sweeps through the unsorted part to find the minimum. Both can involve a lot of work, and both have quadratic worst-case running time.

Anna
There’s a more powerful way to solve certain problems: recursion. Iteration means repeating steps with a loop. Recursion means a function calls itself, usually on a smaller version of the problem.

Michael
Binary search can be expressed recursively: search the left half or the right half by calling the search procedure again on that half. The input gets smaller each time, which is what keeps this from being an endless repetition.

Anna
A recursive function needs a base case—a condition that stops the self-calls. Without one, the function could keep calling itself forever. This is a key idea: solve smaller versions until you reach a case simple enough to handle directly.

Michael
A pyramid gives us a concrete example. A pyramid of height four can be described as a pyramid of height three plus one row. Height three is height two plus one row, and so on. At height zero, there’s nothing to draw—that’s the base case.

Anna
An iterative program can draw that left-aligned pyramid with a loop for the rows and a nested loop for the hashes in each row. A recursive version instead calls draw with height minus one, then prints the current row.

Michael
The order is important. For height four, the function first calls itself for height three, then height two, then height one. Once it reaches the base case, the calls return in reverse order, printing rows of one, two, three, and then four hashes.

Anna
That’s the ‘down and back up’ shape of recursion. The function’s self-calls build up a sequence of unfinished work; once the smallest case is reached, the program returns through those calls and completes each remaining step.

Michael
We can apply recursion to sorting with merge sort. If the list has just one item, it’s already sorted. Otherwise, sort the left half, sort the right half, and merge the two sorted halves together.

Anna
The merge step uses extra space. It repeatedly takes the smaller of the next available items from the two sorted halves, building a combined list in order. For example, merging 4 and 7 with 2 and 5 produces 2, 4, 5, 7.

Michael
The recursive breakdown continues until the lists have one item each, then merges them into lists of two, then four, and finally one fully sorted list. The number of times we can halve a list of n items is proportional to log n.

Anna
At each level of that process, merging touches all n items. There are about log n levels, so merge sort takes O of n log n. That grows faster than linear time, but much more slowly than n squared for large inputs.

Michael
Merge sort performs the same divide-and-merge process even when the input is already sorted. So its best-case bound is also Ω of n log n. That’s a trade-off: compared with optimized bubble sort, merge sort has a better worst case, but it doesn’t reduce its work as much on an already sorted list.

Anna
When an algorithm’s upper and lower bounds match, we can use theta notation for that running time. Selection sort is Θ of n squared, and merge sort is Θ of n log n, because each has the same growth rate in its best and worst cases.

Michael
So we’ve moved from arrays and simple searches to ways of describing efficiency, better data organization, several sorting strategies, and recursion. The point today isn’t to memorize every detail immediately. It’s to get familiar with the ideas, because we’ll reuse them as we write and analyze more programs.

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