Searching and Sorting Algorithms


Searching and Sorting Algorithms

Anna
Welcome to week three of CS50. Today we’re connecting two big ideas: searching for information and sorting it. An algorithm is a step-by-step set of instructions for solving a problem, and sorting means arranging information by some rule, such as smallest to largest or alphabetically.

Hope
And the point isn’t just to memorize a few famous algorithms. It’s to learn ways of thinking about problems, and how those methods translate into code a computer can actually run.

Anna
Let’s begin with a problem that sounds simple: taking attendance. One approach is to count people one at a time: one, two, three, and so on. Counting by twos is faster, but it still takes a number of steps that grows in proportion to the number of people.

Hope
The cleverer approach is to have everyone start with the number one, pair up, add their numbers, and have one person in each pair sit down. The people still standing repeat that process. Each round combines counts and removes roughly half the participants, until the remaining count represents everyone.

Anna
That’s a divide-and-conquer strategy: reduce the problem by half, then by half again. If the number of people doubled, the process would need only about one additional round; if it quadrupled, about two. That growth is much slower than counting each person individually.

Hope
There’s an important distinction between the idea being efficient and a particular performance being correct. The group’s count was off a little because people can make mistakes while carrying out the steps. Theoretically, though, if each pair adds correctly and no one is missed or counted twice, the method produces the right total.

Anna
We can picture these growth rates on a graph. Put the number of people, or more generally the problem size, on the horizontal axis and the number of steps on the vertical axis. Counting one at a time makes a straight line: every extra person requires another step.

Hope
Counting by twos is also linear. It has a smaller constant factor, so it’s faster, but its steps still grow proportionally with the input size. The divide-and-conquer attendance method grows like a logarithm: multiplying the input by two adds just one halving round.

Anna
That leads to today’s central question: how do we describe an algorithm’s cost? Often we mean running time, but cost could also mean money, storage, or another limited resource. We’ll use broad, standard descriptions of growth rather than counting every tiny operation precisely.

Hope
To understand searching, remember what an array is: a contiguous block of memory whose values sit next to one another. A computer doesn’t simply see every value at once the way we see a diagram. In the basic model we’ll use, it accesses one location at a time.

Anna
And arrays use zero-based indexing. The first element is at location zero, the second at location one, and so on. So an array with seven elements has locations zero through six; in general, an array of size N ends at index N minus one.

Hope
Imagine each array location as a closed locker. We want to know whether one locker contains a particular value, say 50. The input is the lockers and their contents; the desired output is a Boolean answer: true if 50 is present, false if it isn’t.

Anna
The first method is linear search. Start at one end, open each locker in sequence, and check its value. If you find 50, return true; if you reach the end without finding it, return false.

Hope
You can search from left to right or right to left. Without prior information about where the target is, neither direction is fundamentally better. Randomly jumping around might get lucky, but it also means keeping track of which locations you’ve already checked, and it doesn’t reliably improve the search.

Anna
Binary search uses more information: it assumes the data is sorted. Check the middle value. If it’s the target, you’re done; if the target is smaller, continue in the left half; if it’s larger, continue in the right half.

Hope
Each decision discards about half the remaining possibilities, just like the phone-book example. But that only works because the values are ordered. In an unsorted array, seeing a value larger than 50 in the middle tells you nothing reliable about which side contains 50.

Anna
There’s also a corner case: if there are no locations left to search, return false. For an array of N elements, a middle index can be found by dividing the relevant index range by two and rounding down. With seven elements, for example, the middle index is three.

Hope
When searching the left half, stop before the middle location; when searching the right half, start after it. We already checked the middle, so including it again would waste work. This kind of careful boundary handling is important when translating an algorithm into code.

Anna
The pseudocode for linear search is straightforward: for each location from left to right, if that location contains the target, return true. After the loop, return false. That final false matters because we should only claim the target is absent after checking every location.

Hope
A common mistake would be to return false as soon as the first location doesn’t match. A return ends the function’s work, so that would stop the search before checking the rest of the array. The indentation in pseudocode helps show which instructions belong inside the loop and which happen after it.

Anna
In a more compact notation, we might say: for I from zero through N minus one, if the target is at doors bracket I, return true; then, after the loop, return false. The N minus one endpoint follows directly from zero indexing.

Hope
Binary-search pseudocode can express the same repeated logic by saying to search the left half or search the right half. Those instructions mean to apply the search again to a smaller range. We’ll come back to that idea when we talk about recursion.

Anna
Now let’s compare the algorithms by their running times. Big O notation describes an upper bound on growth: roughly, how bad the running time can get as the input becomes large. We often use it to discuss the worst case.

Hope
Linear search is O of N. In the worst case, the target is at the very end, or isn’t present, so we may inspect every one of the N locations. Binary search on sorted data is O of log N, because repeatedly halving the possibilities takes about log base two of N steps.

Anna
In Big O, we focus on the dominant growth term and ignore constant factors and lower-order terms. So O of N divided by two is still O of N, and the base of the logarithm is generally omitted. The reason is that we care most about how the cost grows when N gets very large.

Hope
A few common growth rates to recognize are constant time, O of one; logarithmic, O of log N; linear, O of N; linearithmic, O of N log N; and quadratic, O of N squared. Their curves behave very differently as the problem gets bigger.

Anna
Big O gives an upper bound, while Big Omega gives a lower bound. For linear search, the best case is Omega of one: the first location checked could contain the target. For binary search, the best case is also Omega of one: the target could be right in the middle on the first check.

Hope
If an algorithm’s Big O and Big Omega bounds are the same, we can describe it with Big Theta. That says its growth is tightly bounded on both sides. Big O, Big Omega, and Big Theta are all forms of asymptotic notation, which describes behavior as the input size grows.

Anna
There’s also a practical design choice hidden in the comparison. Binary search is fast, but the data must be sorted. If you have to sort a large collection just to search it once, the sorting cost may outweigh the savings. If you’ll search repeatedly, sorting once and reusing the order can make sense.

Hope
Exactly. A service that searches the same data many times can spread the cost of sorting across all those searches. And sometimes a slower but correct program is a reasonable choice if the input is small or the result can wait. The useful thing is to make that trade-off knowingly.

Anna
Let’s translate linear search into C. With an integer array, we can use a for loop starting at index zero and continuing while I is less than the array’s length. At each location, compare the stored number with the number the user requested.

Hope
If they match, print that the value was found and return success from main. If the loop finishes without a match, print that it wasn’t found and return a nonzero exit status. In C, main returns an integer; zero conventionally indicates success.

Anna
If we initialize an array with values inside curly braces, the compiler can infer the number of elements by counting them. You can specify the size too, but letting the compiler infer it avoids accidentally giving the wrong size.

Hope
Searching strings looks similar at first, but there’s a catch: in C, you can’t compare two strings for equality with the equals-equals operator. A string consists of multiple characters, and comparing strings requires checking their contents.

Anna
The string.h library provides strcmp, short for string compare. It compares two strings and returns zero when they’re equal; a negative or positive value indicates an ordering between them. For a search where we only care about equality, we check whether strcmp returns zero.

Hope
That ordering can be useful too: strcmp can help compare strings for sorting, based on the character values. But for linear search, equality is enough. And remember to include string.h, or the compiler won’t have the declaration for strcmp.

Anna
A phone book example reveals another design issue. If names and phone numbers live in two separate arrays, location zero in one array has to correspond to location zero in the other. The programmer has to keep both arrays the same size and in matching order.

Hope
That’s fragile, especially as the data grows. Related information should be kept together. C lets us define our own data type using a structure, or struct, and a typedef can give that custom type a convenient name.

Anna
For example, define a person with a string name and a string number. Then create an array of people. Each array element now groups one person’s name and number together, and dot notation accesses a field, such as people bracket I dot name.

Hope
Phone numbers should generally be stored as strings, not integers. They may contain plus signs, dashes, or parentheses, and a leading zero can be meaningful even though it has no value in ordinary arithmetic. A string preserves those characters as written.

Anna
With an array of people, we can linearly search each person’s name using strcmp. When the name matches, we print the number from that same person structure. This is called encapsulating related data: keeping the pieces that belong together in one unit.

Hope
Searching is only half the story. Binary search depends on sorted input, so we also need to ask how expensive sorting is. Our sorting problem takes unsorted values as input and should produce those values in ascending order.

Anna
The first method is selection sort. Find the smallest value in the unsorted portion, swap it into the first available position, then repeat for the remaining portion. After each pass, one more value is fixed in its final location.

Hope
For an array of N values, the first pass examines about N minus one values, the next about N minus two, then N minus three, continuing down. The total is N minus one plus N minus two and so on, which is proportional to N squared.

Anna
So selection sort is O of N squared. It also remains Omega of N squared, even if the input is already sorted, because this version still scans the remaining values on every pass. Since the upper and lower bounds match, its running time is Theta of N squared.

Hope
The second method, bubble sort, compares neighboring values and swaps them when they’re out of order. As it moves through the array, large values gradually bubble toward the end. Repeat passes until the list is sorted.

Anna
One pass compares locations I and I plus one. That’s why I only goes through N minus two: if I were N minus one, I plus one would be outside the array. The repeated passes lead to about N times N work, so bubble sort’s worst-case time is O of N squared.

Hope
We can improve bubble sort by tracking whether a pass made any swaps. If a complete pass makes none, the list is already sorted, so stop. That gives bubble sort a best-case lower bound of Omega of N, because it still has to inspect the list once.

Anna
That improvement doesn’t change the worst case: a badly ordered list may still require many passes, so O of N squared remains. Selection sort and bubble sort both make lots of repeated comparisons, which becomes painful as the input grows.

Hope
A fundamentally different technique is recursion. A recursive function calls itself. That can sound like an invitation to an infinite loop, so a recursive solution needs a base case that stops the process, and a recursive case that makes progress by working on a smaller problem.

Anna
Binary search is a natural example. If the target isn’t in the middle, search the left or right half using the same method. The recursive call receives fewer locations than before, and eventually either finds the target or reaches the base case where nothing remains.

Hope
A pyramid can be described recursively too. A pyramid of height four is a pyramid of height three plus one row; height three is height two plus one row; and so on. The base case is a pyramid of height one, a single row.

Anna
There’s a useful contrast between iteration and recursion. Iteration uses loops to repeat instructions; recursion solves a problem by calling the same function on a smaller version. Both can produce the same result, but recursion can express the structure of a problem more elegantly.

Hope
For a simple Mario-style pyramid, an iterative solution uses nested loops: an outer loop for rows and an inner loop to print the right number of blocks. A recursive version draws a pyramid of height N minus one, then prints one more row.

Anna
That recursive version must stop when the height reaches zero or less. Without that base case, each call would make another call forever. Recursion also uses memory for each active function call, so an extremely large input can exhaust available memory, even if an iterative version would not have the same problem.

Hope
Now we can put recursion to work on a faster sorting algorithm: merge sort. Its recipe is: if there’s only one value, stop, because a one-value list is already sorted. Otherwise, sort the left half, sort the right half, and merge the two sorted halves.

Anna
The merge step is the key. Look at the first unprocessed value in each sorted half, choose the smaller one, and move it into the output. Then advance in the half it came from and repeat. Because each value is considered once, merging two halves takes a number of steps proportional to N.

Hope
For example, if one half is one, three, four, six, and the other is zero, two, five, seven, compare the first available values. Take zero, then one, then two, then three, and continue until the merged result is zero through seven.

Anna
Merge sort applies that idea recursively. Split a list of eight into halves, keep splitting until the sublists have one value, then merge neighboring sorted pieces. Those pieces merge into sorted groups of two, then four, and finally one sorted list of eight.

Hope
The work happens across about log base two of N levels, because the list is repeatedly divided in half. At each level, merging across all the pieces accounts for about N work. Multiply those together and merge sort takes O of N log N time.

Anna
In the version we’ve described, there’s no special early-exit optimization, so the lower bound is also Omega of N log N. That makes the tight bound Theta of N log N. It grows more slowly than the quadratic time of selection sort and bubble sort for large inputs.

Hope
There’s a trade-off: merging requires extra space to hold the combined result, in the demonstration effectively another shelf of values. So merge sort saves time compared with those quadratic algorithms, but uses additional memory.

Anna
That’s the theme tying everything together: algorithms are about both correctness and design. Linear search works without sorted data, while binary search is much faster when data is sorted. Sorting itself has costs, and different sorting strategies trade time, memory, and simplicity in different ways.

Hope
And the growth-rate notation gives us a common language for comparing those costs. Linear search is O of N; binary search on sorted data is O of log N; selection and bubble sort are O of N squared in the worst case; and merge sort is Theta of N log N in the version we studied.

Anna
We’ve moved from a human counting demonstration to arrays, searching, asymptotic notation, C strings and structures, and several sorting algorithms. The practical question is always: does the method produce the right result, and how will its cost grow as the problem gets larger?

Hope
That’s a strong foundation for the next steps in computer science: not just writing code that works, but choosing a method that works well for the data and the task at hand.

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