Memory and Pointers
Algorithms, Efficiency, Data Structures, and Recursion
Memory, arrays, and searching
A computer stores data in memory, usually represented as a sequence of bytes. Thinking of memory as numbered locations makes it possible to organize related values into an array: a group of elements stored in order and accessed by their positions, or indices.
An array is useful for searching, but a computer does not take in all its contents at once as a person might when glancing at a list. It examines elements step by step. If a program needs to determine whether an array contains a particular value, it must use an algorithm to decide which elements to inspect and in what order.
The search problem can be described as:
Input: An array and a target value.
Output: A Boolean result indicating whether the target is present.
Linear search
Linear search examines array elements one at a time, from one end to the other, until it finds the target or reaches the end.
A typical procedure is:
Start at the first element.
Compare the current element with the target.
If they match, report success.
Otherwise, move to the next element.
If the end is reached without a match, report failure.
For an array with n elements, linear search may have to inspect all n elements. Its worst-case running time is therefore O(n). The target might instead be the first element, so its best-case running time is Ω(1).
Linear search does not require the array to be sorted. This makes it applicable to arbitrary arrays, but it can require many comparisons.
Binary search
Binary search repeatedly divides a search area in half. It can be used only when the array is sorted.
For each step:
Inspect the middle element of the remaining search area.
If it is the target, report success.
If the target is smaller, continue in the left half.
If the target is larger, continue in the right half.
If no elements remain, report failure.
Because each comparison eliminates approximately half of the remaining elements, binary search takes O(logn) time in the worst case. If the target happens to be at the first middle element examined, it takes only one comparison, so its best case is Ω(1).
The sorting requirement matters: binary search is not automatically a better choice than linear search. If the data must first be sorted, sorting has a cost. Whether sorting is worthwhile depends on how often the data will be searched and whether the cost of sorting is offset by faster later searches.
Measuring algorithm efficiency
An algorithm’s running time describes how its work grows as the input grows. It can be measured in elapsed time, but computer scientists often reason about the number of steps an algorithm performs. Step counts make it easier to compare approaches without depending on a particular computer.
Big O: an asymptotic upper bound
Big O notation describes an asymptotic upper bound on an algorithm’s growth. It is commonly used to express worst-case performance: how much work an algorithm may require when given a difficult input.
For example:
Linear search has a worst-case bound of O(n).
Binary search has a worst-case bound of O(logn).
Bubble sort and selection sort have worst-case bounds of O(n2).
Merge sort has a worst-case bound of O(nlogn).
Big O focuses on how an algorithm behaves for large inputs. It intentionally ignores constant factors and lower-order terms. Thus, an algorithm taking about 2n steps is still described as O(n): both expressions grow linearly, and the factor of 21 becomes less important as n increases.
The base of a logarithm is also generally omitted in this context. Logarithms with different fixed bases differ only by a constant factor, so they have the same asymptotic growth rate.
Omega: an asymptotic lower bound
Omega notation, written Ω, describes an asymptotic lower bound. It is often used to express best-case performance: the minimum work an algorithm can perform for favorable input.
Examples include:
Linear search has best-case time Ω(1) if the target is first.
Binary search has best-case time Ω(1) if the target is the first middle element.
Counting every element in an array requires Ω(n) work, because every element must be examined to produce an accurate count.
A good best case does not necessarily mean an algorithm is good overall. A program that runs quickly only for especially convenient inputs may still be slow on typical or difficult inputs. Worst-case performance is often emphasized because it gives a useful guarantee about how bad performance can become.
Theta: a matching upper and lower bound
Theta notation, written Θ, describes a tight asymptotic bound: the upper and lower bounds have the same growth rate.
For example:
Selection sort, as described, performs its repeated scans regardless of whether the input is already sorted. Its best and worst cases are both Θ(n2).
Merge sort performs its divide-and-merge process even when the input is already sorted. Its best and worst cases are both Θ(nlogn).
A modified bubble sort can stop after a pass with no swaps. This gives it a best case of Ω(n) for an already sorted list, while its worst case remains O(n2).
Arrays, strings, and related data in C
Initializing and traversing arrays
An array can be initialized by assigning to each element individually or by listing the values together in curly braces. For example:
int numbers[] = {4, 8, 15, 16, 23, 42};A loop can examine each element in turn:
for (int i = 0; i < 6; i++)
{
if (numbers[i] == 50)
{
printf("Found\n");
return 0;
}
}
printf("Not found\n");
return 1;This implements linear search. The index begins at 0, so an array of six elements has valid indices from 0 through 5. A loop that attempts to access an index outside that range can read beyond the array’s bounds.
In C programs, returning 0 from main conventionally indicates success; a nonzero return value conventionally indicates failure. These are conventions used to communicate the program’s outcome to the environment running it.
Comparing strings
In C, a string is not a simple primitive value like an integer. It is represented as a sequence of characters. Consequently, == does not provide the intended way to test whether two strings contain the same text.
The function strcmp, declared in string.h, compares strings by their contents:
It returns
0when the strings are equal.It returns a negative value when the first string comes before the second alphabetically.
It returns a positive value when the first string comes after the second alphabetically.
For equality testing, the important condition is that the result equals 0:
if (strcmp(names[i], "Emma") == 0)
{
printf("Found\n");
return 0;
}A search program must stop or otherwise control its output after finding a match. Printing “Found” inside the loop and then unconditionally printing “Not found” after the loop can produce contradictory output. Returning immediately upon success is one way to avoid this.
Representing phone numbers
A phone number is generally better stored as a string than as an integer. Although it may look numeric, it is an identifier or formatted sequence, not a quantity used in arithmetic. It may contain:
Leading zeros, which would be lost if treated numerically.
Dashes, spaces, parentheses, or plus signs.
Other formatting that is meaningful as text.
This illustrates an important modeling principle: a value’s appearance does not necessarily determine its appropriate data type. A phone number looks like a number, but its use and possible characters make a string a better representation.
Keeping related values together with a structure
Storing names in one array and corresponding phone numbers in another can work only if the two arrays remain in matching order. If one array is rearranged without the other, a name can become associated with the wrong number.
C structures allow related fields to be grouped together as one record. A custom type can be defined with typedef and struct:
typedef struct
{
string name;
string number;
} person;Each person contains both a name and a phone number. An array of such records keeps each person’s information together:
person people[4];A field is accessed with the dot operator:
people[0].name = "Emma";
people[0].number = "617-555-0100";Grouping related fields makes it safer to move, sort, or otherwise manipulate records: the associated data moves together. This idea is useful in larger programs and databases, where each item may contain many related pieces of information.
Sorting algorithms
Sorting rearranges elements into an order, such as smallest to largest. A sorted list can make later tasks, including binary search, more efficient. However, sorting itself has a cost, so its benefit depends on the application and how often the sorted data will be used.
Bubble sort
Bubble sort repeatedly compares adjacent elements and swaps a pair when it is out of order. As passes continue, large elements move toward the end of the list, much as though they were bubbling upward.
A pass examines neighboring elements from one end of the list to the other. Repeating these passes gradually places elements in their correct positions. A typical version makes up to n−1 passes, with up to about n−1 comparisons per pass, giving a worst-case running time of O(n2).
In the unoptimized version, the algorithm performs its prescribed passes even if the list was already sorted. Its best case is therefore also Θ(n2). An improvement is to record whether any swaps occurred during a pass:
If at least one swap occurred, the list may still be out of order, so another pass is needed.
If no swaps occurred, the list is sorted, and the algorithm can stop.
With this improvement, an already sorted list takes one pass of adjacent comparisons, or Ω(n) work, while the worst case remains O(n2).
Selection sort
Selection sort builds a sorted portion of the array one position at a time:
Find the smallest element in the unsorted portion.
Swap it into the next position in the sorted portion.
Repeat on the elements that remain unsorted.
On the first pass, the algorithm scans the whole list for its smallest element. On the next pass, it scans the remaining elements, and so on. The work is proportional to a sum such as
which grows quadratically. The exact count depends on the implementation’s scan boundaries, but the asymptotic running time is Θ(n2).
Selection sort does not gain a better best case simply because the input is already sorted. It still needs to inspect the remaining elements on each pass to determine which one is smallest. Unlike optimized bubble sort, it does not naturally stop early just because the list is in order.
Selection sort and bubble sort use different strategies—selecting the next smallest item versus fixing adjacent inversions—but both have quadratic running time in the general case.
Recursion
Recursion is a technique in which a function calls itself. A recursive solution describes a problem in terms of smaller instances of the same problem.
A recursive function needs two essential components:
A base case, which handles a situation directly and stops further recursive calls.
A recursive case, which reduces the problem and calls the function again.
Without a base case, the function can keep calling itself indefinitely. The recursive calls also have to make progress toward that base case, typically by operating on a smaller input.
Recursive definitions and a pyramid example
A left-aligned pyramid of height h can be defined in terms of a smaller pyramid:
A pyramid of height h consists of a pyramid of height h−1, followed by one row containing h bricks.
A pyramid of height 0 contains nothing.
This definition can be implemented with a recursive drawing function:
void draw(int h)
{
if (h == 0)
{
return;
}
draw(h - 1);
for (int i = 0; i < h; i++)
{
printf("#");
}
printf("\n");
}For a height of four, the function first calls itself with height three, then height two, then height one, and finally height zero. The base case returns immediately at height zero. As the calls finish and return, each earlier call prints its row, producing rows of one, two, three, and four bricks.
The recursive calls therefore proceed downward toward the base case, while the rows are printed as the calls return. This explains how the program can generate the full structure even though each individual call prints only one row.
Recursion and divide-and-conquer
Binary search can also be understood recursively. If the target is not in the middle of a sorted list, the algorithm searches only the relevant half. Each recursive step handles a smaller problem than the one it was given.
This is an example of divide and conquer:
Divide a problem into smaller parts.
Solve the smaller parts.
Combine their results if necessary.
Recursion is useful when a problem has a natural self-similar structure. It is not automatically better than iteration, however; recursive calls have costs, and the recursive solution must have valid stopping conditions.
Merge sort
Merge sort sorts a list by dividing it into smaller lists, sorting those lists, and merging the sorted results.
Its procedure is:
If the list contains one item, return: a one-item list is already sorted.
Sort the left half recursively.
Sort the right half recursively.
Merge the two sorted halves into one sorted list.
The one-item case is the base case. The recursive cases reduce the input by dividing it into halves.
How merging works
When two already-sorted lists are merged, the algorithm repeatedly compares their next unprocessed elements and copies the smaller one into the output. For example, merging the sorted lists [4, 7] and [2, 5] proceeds by selecting the smallest available element at each step:
Compare 4 and 2; take 2.
Compare 4 and 5; take 4.
Compare 7 and 5; take 5.
Copy the remaining 7.
The result, [2, 4, 5, 7], is sorted. Merging two lists requires auxiliary space to hold the combined output.
Why merge sort is faster asymptotically
The list is repeatedly divided in half. A list of size n can be halved approximately logn times before reaching lists of size one. At each level of division, merging processes all n elements across the sublists.
Thus, merge sort performs work proportional to n elements at each of about logn levels:
This is asymptotically faster than the quadratic running time of bubble sort and selection sort for sufficiently large inputs. In the version described, merge sort carries out its divide-and-merge process even if the original list is already sorted. Its best and worst cases are therefore both Θ(nlogn).
Comparing the sorting approaches
Bubble sort
Strategy: Compare adjacent elements and swap out-of-order pairs.
Worst case: O(n2).
Best case without early stopping: Θ(n2).
Best case with a no-swaps stopping condition: Ω(n).
Selection sort
Strategy: Find and place the next smallest element.
Worst case: Θ(n2).
Best case: Θ(n2), because the scans continue even for an already sorted list.
Merge sort
Strategy: Recursively sort two halves, then merge them.
Worst case: Θ(nlogn).
Best case in the described version: Θ(nlogn).
Additional consideration: Merging requires extra space for the combined results.
The comparison illustrates that a correct algorithm is not necessarily an efficient one. Algorithm design considers both whether the output is correct and how the required work grows as the input becomes larger. Choosing an algorithm also involves trade-offs: an algorithm may be faster in the worst case but do work that could have been avoided on especially favorable input.
Algorithms and real-world outcomes
Algorithms are not limited to searching or sorting. They can determine how real-world decisions are computed, including how votes are counted in elections.
A plurality election selects the candidate with the most votes. A ranked-choice or runoff-style election instead uses voters’ preferences and applies additional rules to determine a winner. Different counting algorithms can produce different outcomes from the same voters’ rankings, so the choice of algorithm can have practical consequences.
This is another reason algorithms must be understood not only as code, but also as explicit procedures whose assumptions and effects matter.

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