Searching and Sorting Algorithms
Searching, Sorting, Efficiency, and Recursion
Algorithms and problem-solving
An algorithm is a finite, step-by-step procedure for solving a problem. Sorting algorithms order information according to a rule, such as numerical order or alphabetical order; search algorithms look for particular information.
A useful algorithm must be considered in two ways:
Correctness: Does it produce the right answer?
Efficiency: How does its use of time and other resources grow as the problem gets larger?
The same problem can often be solved by several algorithms. Comparing them helps determine which is appropriate for a particular situation.
Measuring algorithmic growth
Problem size and running time
Algorithmic running time describes how the amount of work changes as the problem size grows. Problem size is often represented by N, such as the number of items in an array. Work can be measured in steps, comparisons, or another consistent unit.
Some tasks grow proportionally to the number of items. For example, checking every item in a list of N items may require N checks. Other tasks grow much more slowly: repeatedly halving a problem of size N takes about log2N rounds.
A divide-and-conquer attendance-counting method illustrates this idea. Each person begins with a count of 1. In each round, people pair up, add their counts, and one person in each pair sits down. The remaining participants repeat the process. Each round roughly halves the number of active participants, so the number of rounds grows logarithmically with the group size. This describes the number of parallel rounds; the fact that many pairs work at the same time is essential to the method’s speed.
By contrast, counting one person at a time takes a number of steps proportional to the number of people. Counting by twos is still linear: it reduces the work by a constant factor, but the number of steps still grows in proportion to the input size.
Big O notation
Big O notation describes an asymptotic upper bound on an algorithm’s growth: broadly, how quickly its work can grow as the input becomes large. It is commonly used to discuss a worst-case running time, although Big O itself expresses an upper bound rather than specifying a particular case.
Common growth rates include:
O(1): constant work, independent of input size.
O(logN): logarithmic growth; the problem is repeatedly reduced, often by half.
O(N): linear growth; work grows proportionally to the input size.
O(NlogN): work grows in proportion to the input size times a logarithmic factor.
O(N2): quadratic growth; work is proportional to the square of the input size.
When comparing growth rates, Big O focuses on the dominant term and disregards constant factors and lower-order terms. For example, O(N/2) and O(N) are both linear, so they belong to the same Big O class. Likewise, the base of a logarithm is normally omitted because changing it only changes the result by a constant factor.
The practical difference between growth rates becomes more significant as N grows. An algorithm that is acceptable for a few dozen values may be too slow for millions of values.
Omega and Theta notation
Omega notation, written Ω, describes an asymptotic lower bound: broadly, how little work an algorithm may require in its most favorable case.
Theta notation, written Θ, describes a tight asymptotic bound. It applies when the upper and lower bounds have the same growth rate. For example, if an algorithm’s running time is both O(N2) and Ω(N2), it is Θ(N2).
Big O, Omega, and Theta are forms of asymptotic notation: they describe how performance behaves as the input grows without focusing on exact step counts for a particular small input.
Arrays and accessing data
An array is a sequence of values stored in contiguous memory locations—that is, the values are stored next to one another. In a typical programming model, code accesses an array one value at a time rather than viewing every value simultaneously.
Array locations use zero-based indexing. The first item is at index 0, the second at index 1, and so on. For an array containing N items, the final valid index is N−1. Thus, an index of 6 refers to the seventh item and requires an array with at least seven elements.
This indexing convention is important when writing loops: a loop that visits every element of an array with N items generally uses indices from 0 through N−1.
Searching
Linear search
Linear search checks items one at a time until it finds the target or reaches the end of the collection. It can search from left to right or right to left; either direction has the same general growth rate if the data has no useful ordering.
A general form of linear search is:
For each item in the collection:
If the item is the target:
Return true
Return falseThe final return false is essential. If the search reaches the end without finding the target, it can then correctly report that the target is absent.
A common correctness error is returning false as soon as the first item fails to match. That would stop the search before later items had been checked. A function’s return ends that function’s execution, so it must not return failure until all possible locations have been considered.
For an array with N items:
Worst case: The target is last or absent, so the search may inspect all N items. The running time is O(N).
Best case: The target is first, so only one item is inspected. The running time is Ω(1).
Linear search works whether or not the data is sorted.
Binary search
Binary search repeatedly checks the middle item and discards the half that cannot contain the target. It requires the data to be sorted according to the same ordering used in the comparisons.
A general binary-search procedure is:
If no items remain to be searched, return
false.Check the middle item.
If the middle item is the target, return
true.If the target is smaller than the middle item, search the left portion.
If the target is larger than the middle item, search the right portion.
Repeat the process on the remaining portion.
For an array indexed from 0 through N−1, the middle index can be calculated by dividing the relevant range by 2 and using an integer index. For an odd number of items, this chooses the central item; integer division effectively rounds down.
The already-checked middle item must be excluded from the next search range. If the target is smaller, the remaining range ends at middle - 1; if it is larger, the remaining range begins at middle + 1.
Each comparison cuts the remaining search range roughly in half. Therefore:
Worst case: Binary search takes O(logN) steps.
Best case: The target is the first middle item checked, so the running time is Ω(1).
Binary search is not correct on unsorted data. Its decisions depend on the guarantee that smaller values are on one side and larger values are on the other. Without that ordering, discarding half of the data may discard the target.
Choosing whether to sort before searching
Binary search is faster than linear search when the data is already sorted and there are enough items or searches to make its advantage useful. But sorting also takes time.
The right choice depends on how the data will be used:
If a collection will be searched only once, sorting it first may cost more than simply performing a linear search.
If it will be searched many times, sorting once and then using binary search repeatedly may justify the initial sorting cost.
If the data is already sorted, binary search can be used without that preprocessing cost.
This illustrates a general design principle: resource decisions should account for the entire workload, not just the cost of one operation. Time and memory are both limited resources, and an algorithm may trade one for the other.
Searching arrays in C
Linear search for integers
An integer array can be searched with a loop that checks each value against the target. For example:
int numbers[] = {20, 500, 10, 5, 100, 1, 50};
int n = get_int("Number: ");
for (int i = 0; i < 7; i++)
{
if (numbers[i] == n)
{
printf("Found\n");
return 0;
}
}
printf("Not found\n");
return 1;The array size can be inferred by the compiler when values are supplied in the initializer. For example, the compiler can count the values between the braces in int numbers[] = {...};. Hard-coding the loop limit separately can be error-prone if the array later changes.
In main, returning 0 conventionally indicates success, while a nonzero value indicates that something did not succeed. These return values serve as the program’s exit status.
Comparing strings
In C, == is not the appropriate way to compare the contents of two strings. A string can contain many characters, and determining whether two strings are equal requires comparing their characters.
The strcmp function, declared in the string.h header, compares two strings:
#include <string.h>
if (strcmp(strings[i], target) == 0)
{
printf("Found\n");
}Its return value indicates the comparison:
A value of
0means the strings are equal.A negative value means the first string precedes the second under the comparison.
A positive value means the first string follows the second.
The ordering is based on character values, so it can also be used to help order strings. For a search that only needs to test equality, the important check is whether strcmp returns 0.
Representing phone numbers
A phone number may contain punctuation such as +, hyphens, or parentheses. It may also begin with a zero that must be preserved. Such values should be stored as strings rather than integers: integers represent quantities and do not retain formatting or leading zeros.
Structuring related data
The problem with separate arrays
A phone book could be represented by one array of names and another array of phone numbers. This design relies on both arrays having the same length and matching positions: the name at index i must correspond to the number at index i.
That relationship is easy to accidentally break. If one array is changed without making the matching change to the other, a name could be associated with the wrong number.
Structures and encapsulation
A structure groups related fields into one custom data type. In C, typedef struct can define a type such as person, containing both a name and a phone number:
typedef struct
{
string name;
string number;
} person;An array of these structures stores complete records together:
person people[3];A field is accessed using dot notation:
people[0].name = "Kelly";
people[0].number = "+1 617 495 1000";A search can compare the name field of each person with a user’s input. Once a match is found at index i, the corresponding phone number is available at people[i].number.
Grouping the fields encapsulates related information: each array element represents one person and contains that person’s associated data. This makes the relationship explicit rather than relying on two separate arrays to remain aligned.
Sorting
Sorting takes unsorted data as input and produces the same data in a specified order. Three sorting algorithms illustrate different approaches and different growth rates: selection sort, bubble sort, and merge sort.
Selection sort
Selection sort repeatedly finds the smallest value in the unsorted portion of the array and moves it to the next position in the sorted portion.
A general procedure is:
For each position i from 0 through N - 1:
Find the smallest value from position i through N - 1
Swap it with the value at position iAt the first pass, the algorithm searches the whole array and places the smallest value at index 0. At the next pass, it searches the remaining portion and places the next-smallest value at index 1. It continues until the array is sorted.
The algorithm swaps the selected value with the value at the current position. It cannot simply insert a new space into the array, because the array has a fixed number of allocated locations; moving values must preserve the existing storage arrangement.
Selection sort may repeatedly inspect values that it has seen before. It uses little extra memory for the search itself, but it performs many comparisons.
For an array of N elements, the number of comparisons is:
This grows quadratically, so selection sort has:
Upper bound: O(N2)
Lower bound: Ω(N2)
Tight bound: Θ(N2)
Even if the input is already sorted, ordinary selection sort still scans the unsorted portion at every pass. It therefore does not gain a faster best case merely because the values start in order.
Bubble sort
Bubble sort repeatedly compares neighboring values and swaps them when they are out of order. During a pass through the array, large values move toward the end. The largest remaining value effectively “bubbles” into its final position.
A general form is:
Repeat passes through the array:
For each adjacent pair:
If the pair is out of order:
Swap the pairIf an array has valid indices from 0 through N−1, a comparison at index i checks the values at i and i+1. Therefore, i must stop at N−2; allowing it to reach N−1 would make the algorithm access index N, which is outside the array.
In the worst case, bubble sort makes roughly N passes, each involving roughly N comparisons. Its upper bound is therefore O(N2).
A useful optimization is to stop if a complete pass makes no swaps. If no adjacent pair needs to be swapped, the array is already sorted, so another pass is unnecessary. With this optimization:
Best case: An already-sorted array requires one pass to verify that no swaps are needed, giving Ω(N) work.
Worst case: The algorithm may still require many passes, giving O(N2) work.
The optimized bubble sort’s best and worst cases differ, so it does not have one tight bound that describes both.
Merge sort
Merge sort uses divide and conquer. It divides a list into smaller parts, sorts those parts, and merges the sorted results.
Its central steps are:
If the list has one item, stop: it is already sorted.
Sort the left half.
Sort the right half.
Merge the two sorted halves.
The one-item case is the base case. The other steps create smaller sorting problems, which are solved recursively.
Merging sorted halves
Suppose two halves are already sorted. To merge them:
Begin at the leftmost unprocessed item in each half.
Compare those two items.
Copy the smaller one into the output.
Advance the position in the half from which the item was taken.
Repeat until all items have been copied.
Because each position advances only forward, every element needs to be considered only once during a merge. Merging two sorted halves containing a total of N items takes O(N) work.
Merge sort’s running time
Each level of merge sort does a total of O(N) work: across all the merges at that level, each element is processed once. The number of levels is approximately log2N, because the problem size is repeatedly divided by two. Thus the total running time is:
For the described merge sort, the lower bound has the same growth rate, so the tight bound is:
Merge sort generally requires additional memory to hold merged results. The algorithm’s reduced comparison work is therefore achieved at the cost of extra space; the demonstration uses an auxiliary area large enough to hold the values being merged.
Comparing sorting algorithms
Selection sort: Θ(N2); repeatedly searches for the next smallest value.
Bubble sort: O(N2) in the worst case; with an early-stop check, it can finish in Ω(N) when the list is already sorted.
Merge sort: Θ(NlogN); recursively sorts halves and merges them, using additional memory.
As the input grows, merge sort’s NlogN growth is substantially more favorable than the quadratic growth of selection sort and bubble sort.
Recursion and iteration
What recursion means
A recursive function is a function that calls itself. Recursion is useful when a problem can be expressed in terms of smaller versions of the same problem.
A recursive definition needs two kinds of cases:
A base case gives an immediate answer and stops the recursion.
A recursive case calls the function on a smaller problem.
Without a base case, a function could call itself indefinitely. Without a smaller problem, each call could repeat the same work without making progress.
Binary search illustrates recursion: after comparing against the middle item, it searches only the left or right portion. Each call handles a smaller range, eventually reaching either the target or an empty range.
Recursive and iterative search
A recursive description of binary search says, in effect, “search the relevant half again.” An iterative description uses a loop to repeat the same process.
Both can express the same algorithm. Iteration makes the repetition explicit through loops; recursion expresses it through repeated function calls on smaller problems.
Recursive pyramids
A pyramid of height N can be described as a pyramid of height N−1 followed by one additional row. A pyramid of height one is a single row, and a height of zero requires no drawing. This gives a recursive structure:
Draw a pyramid of height n:
If n is 0:
Stop
Draw a pyramid of height n - 1
Print one row containing n blocksAn iterative version instead uses loops. For a left-aligned pyramid, an outer loop handles each row, and an inner loop prints the required number of blocks for that row. Recursion can express the same structure more directly, while iteration can avoid the extra memory required by repeated function calls.
Recursion and memory
Each recursive call requires the computer to keep track of that call’s state, including its local variables and where execution should continue afterward. These records consume memory. If recursion continues too deeply, the program can exhaust its available call-stack memory and fail with a stack overflow.
An iterative version of the same task may use less call-stack memory because it does not create a new function call for every step. Recursion can make a solution conceptually elegant, but it carries a memory cost that must be considered.
Key principles
A problem’s size determines what performance differences matter; growth rates become increasingly important for large inputs.
Linear search works on unsorted data and takes O(N) time in the worst case.
Binary search takes O(logN) time in the worst case, but only when the data is sorted.
Sorting before searching is worthwhile only when its cost is justified by the number and purpose of later searches.
Arrays use zero-based indices, and the last index in an array of N items is N−1.
Structures keep related fields together, reducing dependence on separate arrays remaining aligned.
Selection sort and bubble sort have quadratic worst-case running times; merge sort runs in Θ(NlogN) time but requires extra memory.
Recursive algorithms require a base case and must make progress toward it by solving smaller problems.

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