Searching and Sorting Algorithms
Searching, Sorting, and Measuring Algorithms
An algorithm is a sequence of steps for solving a problem. Sorting and searching are two fundamental examples: sorting puts information into an order, while searching looks for a particular item. Algorithms matter not only because they produce answers, but also because different methods can take very different amounts of time or memory to produce them.
A useful way to study an algorithm is to ask two questions:
- Does it produce the correct answer?
- How much work does it require as the problem grows?
The first question concerns correctness. The second concerns efficiency. Both shape the design of useful programs.
Divide and Conquer: Counting by Combining
Imagine counting the people in a room one at a time. Each person contributes one count, so adding more people adds roughly the same amount of work per person. Counting two at a time reduces the work, but still requires moving steadily through the group.
A different method is to have everyone begin with the number 1, pair up, add the two numbers in each pair, and have one person in each pair sit down. The people still standing repeat the process. Each round combines pairs of partial counts, so the number of active counters is roughly halved each time. Eventually, one final number represents the sum of all the original ones.
This is an example of divide and conquer: reduce a problem into smaller pieces, solve or combine those pieces, and continue until the answer is manageable. The same general idea appeared in searching a phone book by repeatedly discarding half of the remaining pages.
If the number of people doubles, the pairing process needs only about one extra round. If the number becomes four times larger, it needs about two extra rounds. That is a much slower increase in work than counting everyone individually. The demonstration can still produce a wrong total if people make mistakes while pairing or adding. The method’s theoretical efficiency does not guarantee a correct execution; the steps must also be carried out correctly.
The cost of an algorithm can mean more than time. It can include memory, money, or another limited resource. The central design question is how those costs grow as the amount of input grows.
An efficient algorithm is not merely one that works on a small example. It is one whose cost remains manageable as the problem becomes larger.
Think About It: If the number of people in a room doubled, which counting method would require the smallest increase in work, and why?
Arrays and the Computer’s View of Memory
An array stores multiple values in adjacent locations in memory. For example, an array can contain several integers or several strings, with its values placed one after another.
A person looking at a drawing of an array may see every value at once. A program, however, typically accesses one location at a time: it goes to a location, reads the value, and then moves to another. A useful analogy is a row of closed lockers. To inspect a value, the computer must open the corresponding locker.
Array positions use zero-based indexing. The first element is at index 0, the second at index 1, and so on. Therefore, an array of N elements has a final index of N−1. An array with seven elements has indices 0 through 6; index 7 would be outside the array.
This matters when writing loops. A loop that visits every position in an array of length N must stop before index N, because that location does not exist.
Linear Search: Inspecting Each Element
Suppose an array contains money in seven lockers, and the goal is to determine whether a particular denomination is present. If the values are not known to be in any order, a straightforward method is to inspect each locker in turn.
This method is called linear search. It checks values one at a time until either the desired value is found or every value has been inspected.
For each location from left to right:
If the desired value is at this location:
Return true
Return false
The placement of the final Return false is important. If the algorithm returned false immediately after the first unsuccessful comparison, it would stop before checking the rest of the array. The correct method returns false only after reaching the end without finding the target.
In an array of N values, the worst case requires checking all N values. The target might be last, or it might not be present at all. The best case requires only one check: the target might be in the first location examined.
Linear search also works when the values are strings or records rather than numbers. The basic strategy remains the same: inspect each element and test whether it matches the target.
Binary Search: Discarding Half the Search Space
When the data is already sorted, there is a faster strategy: binary search. Instead of checking values from one end onward, binary search checks the middle value.
- If the middle value is the target, the search is finished.
- If the target is smaller, only the left half can contain it.
- If the target is larger, only the right half can contain it.
- The process repeats on the selected half.
For example, if the middle value is 20 and the target is 50, the target must be to the right in an array sorted from smallest to largest. The values to the left can be ignored. Each comparison removes roughly half of the remaining search space.
To find the middle position in an array segment, an implementation can use the midpoint of its starting and ending indices. With integer positions, division is rounded down. In a seven-element array indexed from 0 to 6, the midpoint is index 3.
The algorithm should not search the middle element a second time after comparing it. If the target is smaller than the middle value, the remaining left segment ends at the position just before the middle. If the target is larger, the remaining right segment begins just after the middle.
A conceptual version of binary search is:
If there are no values left:
Return false
Check the middle value.
If it is the target:
Return true
If the target is smaller:
Search the left half
Otherwise:
Search the right half
Binary search depends on sorted data. If an array is unsorted, a value smaller than the target might appear on either side of the middle, so the comparison gives no reliable reason to discard a half. Applying binary search to unsorted data can therefore miss the target.
Think About It: Why is a middle-value comparison useful in a sorted array but unreliable in an unsorted one?
Describing Running Time with Asymptotic Notation
The number of steps an algorithm takes is called its running time. Computer scientists often describe running time in broad terms rather than counting every operation exactly. The goal is to understand how the work grows as the input size grows.
Big O: An Upper Bound
Big O notation describes an upper bound on how quickly an algorithm’s cost grows. It is often used to discuss the worst case: the largest amount of work the algorithm may require for inputs of size N.
Linear search has a worst-case running time of O(N) because it may inspect every element. Binary search has a worst-case running time of O(logN) because it repeatedly halves the remaining search space.
A logarithm describes how many times a quantity can be divided by a fixed factor before reaching a small value. For binary search, the relevant factor is 2. For instance, a problem with 8 elements can be halved three times before reaching a single element, and log28=3.
When using Big O, the focus is on the dominant growth term. Constants and smaller terms become less important as N becomes very large. For instance, O(N/2) and O(N) both describe linear growth, while a quadratic term such as N2 eventually grows much faster. The base of a logarithm is also generally omitted in this notation because changing the base changes the value only by a constant factor.
Common growth rates include:
- O(1): constant work, independent of input size
- O(logN): logarithmic growth
- O(N): linear growth
- O(NlogN): linearithmic growth
- O(N2): quadratic growth
Big O does not by itself mean “exactly this many steps.” It describes an upper bound on the rate of growth. For practical comparisons, it helps reveal which algorithms become costly as the input becomes large.
Omega and Theta: Lower and Matching Bounds
Omega notation, written Ω, describes a lower bound: how slowly the running time can grow, or how little work an algorithm may require in a favorable case.
For linear search, the best case is Ω(1) because the target may be the first element checked. Binary search can also have a best case of Ω(1) if the target is already at the middle position examined.
Theta notation, written Θ, is used when the upper and lower bounds describe the same rate of growth. It communicates that the algorithm’s growth is tightly characterized, rather than giving separate upper and lower descriptions.
Together, Big O, Omega, and Theta are forms of asymptotic notation. They describe behavior as the input size grows large, rather than focusing on exact step counts for a particular small input.
Choosing Between Linear and Binary Search
Binary search is faster than linear search for a sufficiently large, sorted array. But sorting the data also costs time. If the data must be sorted only to support one search, sorting first may take more work than simply using linear search.
If the same data will be searched many times, sorting can be worthwhile: its cost can be spread across many searches. This is an example of amortizing a cost over repeated use. The right choice depends on the situation, including how much data there is, how often it will be searched, and whether the data is already sorted.
A slower but correct program may also be reasonable when its work can run unattended and its result is needed only later. But that choice has a risk: if the program contains a bug, a long computation may waste substantial time before the error is discovered. Efficiency decisions are most useful when the trade-offs are understood.
Implementing Search in C
A linear search over integers can be expressed with an array and a loop:
int numbers[] = {20, 500, 10, 5, 100, 1, 50};
int target = get_int("Number to search for: ");
for (int i = 0; i < 7; i++)
{
if (numbers[i] == target)
{
printf("Found\n");
return 0;
}
}
printf("Not found\n");
return 1;
The compiler can infer the number of array elements from the values inside the initializer braces. Writing the length explicitly is possible, but allowing the compiler to infer it avoids the risk of manually specifying a length that does not match the initializer.
For strings, direct comparison with == does not test whether the text in two strings is the same. In C, a string consists of multiple characters, and string equality requires comparing those characters. The strcmp function from string.h performs that comparison:
if (strcmp(strings[i], target) == 0)
{
printf("Found\n");
}
For this function, a return value of zero means the strings are equal. A negative or positive value indicates an ordering difference, which can also be useful when comparing strings for sorting. The appropriate header must be included:
#include <string.h>
String comparison can be used in a phone-book search: examine each stored name, and when the matching name is found, return the associated phone number.
Phone numbers are stored as strings rather than integers because they are identifiers, not quantities for arithmetic. They may contain characters such as plus signs, hyphens, or parentheses. They may also begin with zero; storing such a value as an integer would lose the leading zero.
Structures: Keeping Related Information Together
A phone book can initially be represented with two arrays: one for names and another for numbers. This design relies on the arrays remaining the same length and on each name staying aligned with its corresponding number. That arrangement can work for a small example, but it is easy to disrupt as the data grows or changes.
A structure groups related fields into one custom data type. In C, a structure can define a person with a name and a phone number:
typedef struct
{
string name;
string number;
} person;
An array of person values keeps each person’s information together:
person people[3];
A field is accessed with a dot, as in people[0].name or people[0].number. A search can compare each person’s name with the requested name, then return the number from that same structure.
This design encapsulates related information: a person’s name and number belong together in a single element. It reduces reliance on separately maintained arrays lining up by position.
Sorting: Putting Data in Order
Searching can be faster when data is sorted, but sorting itself has a cost. Sorting algorithms take unsorted input and produce an ordered output, such as values arranged from smallest to largest.
Several algorithms can solve this problem, but they use different strategies and have different running times.
Selection Sort: Repeatedly Choose the Smallest
Selection sort repeatedly finds the smallest value in the unsorted part of the array and places it at the beginning of that part.
The method proceeds as follows:
- Search the entire array for the smallest value.
- Swap it with the value at index 0.
- Ignore the now-correct first position.
- Search the remaining positions for the next-smallest value.
- Swap it into index 1.
- Continue until the array is sorted.
The array cannot simply grow to make room for each chosen value. Its memory space has already been set aside, so the selected value is swapped with the value currently occupying its destination.
For an array of N elements, the first pass compares candidates across roughly N−1 positions. The next pass searches roughly N−2 positions, and later passes inspect progressively fewer values. The total work is described by:
(N−1)+(N−2)+⋯+1=2N(N−1)The dominant term is N2, so selection sort has a running time of Θ(N2). Its best case is also Θ(N2): even if the array is already sorted, the algorithm still performs its scheduled searches for the smallest remaining value. It does not recognize that the work is already complete.
Selection sort is straightforward, but its repeated searches become expensive as the array grows.
Bubble Sort: Swap Neighboring Values
Bubble sort compares neighboring elements and swaps them whenever they are out of order. It repeatedly scans the array from left to right.
For example, if the current pair is 7 and 2, the values are in the wrong order, so they are swapped. The larger value moves one position to the right. As the scan continues, large values move toward the end of the array, or “bubble” upward through the sequence.
A typical procedure repeats scans and compares each position i with its neighbor at i+1. The scan stops before the final index because the neighbor position must remain inside the array: if i were already N−1, then i+1 would be the invalid index N.
In the worst case, bubble sort makes about N passes, with each pass involving a number of comparisons proportional to N. This produces a quadratic running time of O(N2).
A useful improvement is to stop early if a complete pass makes no swaps. If no neighboring values needed swapping, the array is already sorted. With this improvement, the best case is Ω(N), because at least one pass is needed to check the order. The worst case remains O(N2), so the best and worst bounds do not match; the algorithm does not have one Theta bound that describes both cases.
Selection sort and bubble sort are both much slower on large inputs than algorithms with lower growth rates, though bubble sort can detect a fully sorted input when the early-stop improvement is used.
Think About It: Why can an early-stop check improve bubble sort’s best case without changing its worst-case growth rate?
Recursion: Solving a Problem Through Smaller Versions of Itself
A recursive function is a function that calls itself. A recursive algorithm applies the same method to a smaller version of the original problem.
Recursion requires two ingredients:
- A base case gives an immediate answer and stops further recursive calls.
- A recursive case reduces the problem and calls the same function again.
Without a base case, recursive calls can continue indefinitely. Without progress toward the base case, the function may repeatedly solve the same problem without getting closer to a result.
Binary search is naturally described recursively. After checking the middle value, the algorithm searches either the left half or the right half using the same method. The new problem is smaller than the original, so repeated calls eventually reach an empty section or find the target.
The earlier phone-book search can also be written recursively: search the left half or the right half, rather than instructing the algorithm to jump back to a particular earlier line. Both a loop and recursion can express repetition, but they organize the instructions differently. A loop describes repeated steps explicitly; recursion expresses a problem in terms of smaller instances of itself.
A Pyramid as a Recursive Definition
A half-pyramid of height N can be defined as a pyramid of height N−1 followed by one more row. A pyramid of height 1 is a single block, providing a simple base case.
An iterative program might use one loop for each row and a nested loop for the blocks in that row. A recursive program can instead draw the smaller pyramid first and then print the next row. The recursive structure mirrors the definition of the shape.
For example, when drawing a pyramid of height 4, the function first handles height 3, which handles height 2, which handles height $1. Once the base case is reached, the calls return in reverse order, adding the rows needed to complete the pyramid.
Recursion can make code more closely match the structure of a problem, but it uses memory for each active function call. Very deep recursion can use more memory than the computer has available. An iterative version may avoid this particular cost by using loops instead of a long chain of function calls.
Merge Sort: Divide, Sort, and Combine
Merge sort is a recursive sorting algorithm. Its core steps are:
- If the list contains only one value, stop: it is already sorted.
- Sort the left half.
- Sort the right half.
- Merge the two sorted halves.
The first step is the base case. The next two steps repeatedly reduce the problem. The final step combines the results.
The merge step works because both halves are already sorted. One value is examined from the front of each half. The smaller of the two is copied into the next position of the output. Then the process advances in the half from which that value came. It continues until every value has been placed.
For example, if the sorted halves are [1,3,4,6] and [0,2,5,7], the merge compares the values at the front of each half. It takes 0, then 1, then 2, then 3, continuing until the merged result is [0,1,2,3,4,5,6,7].
Each value is considered a constant number of times during one merge, so merging two halves containing a total of N values takes work proportional to N.
For an input of 8 values, the algorithm divides the problem into halves three times before reaching lists of size 1. In general, the number of levels is proportional to log2N. At each level, the merging work across all sublists totals approximately N. Multiplying the work per level by the number of levels gives a running time of:
Θ(NlogN)This is faster growth-wise than the quadratic running times of selection sort and bubble sort for large inputs. Merge sort’s upper and lower bounds match because the described algorithm carries out the division and merging process regardless of whether the original input was already sorted.
Merge sort also uses extra memory to hold the values as the sorted halves are combined. The method therefore trades additional space for reduced running time. This is another example of an algorithmic trade-off: less time may require more memory.
Review: Choosing and Understanding Algorithms
Searching, sorting, and recursion connect several important ideas:
- Linear search checks elements one at a time. It works on unsorted data, takes O(N) time in the worst case, and may take Ω(1) time in the best case.
- Binary search repeatedly discards half of the remaining data. It takes O(logN) time in the worst case, but it requires the data to be sorted.
- Big O, Omega, and Theta describe upper, lower, and matching rates of growth as inputs become large.
- Selection sort repeatedly chooses the smallest remaining element and has Θ(N2) running time.
- Bubble sort repeatedly swaps out-of-order neighbors. It has O(N2) worst-case time, but an early-stop check gives it an Ω(N) best case.
- Recursion solves smaller versions of a problem and needs a base case that ensures the process stops.
- Merge sort uses recursion and merging to sort in Θ(NlogN) time, at the cost of extra memory.
- Arrays store same-type elements in adjacent memory positions and use zero-based indices.
- Structures group related fields, making it easier to keep information such as a person’s name and number together.
The best algorithm depends on more than its speed in isolation. It also depends on whether its assumptions are satisfied, whether preprocessing such as sorting is worthwhile, how often the data will be used, and how much memory is available. Understanding those conditions makes it possible to choose an algorithm deliberately rather than merely choose one that works on a small example.

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