AP® Computer Science Principles · Big Idea 3 · Topic 3.9
Building New Algorithms from Existing Ones
Building a new algorithm often means reusing and recombining pieces you already trust, like a max finder or a sum, rather than writing everything from scratch.
Most algorithms are not invented from nothing. They are assembled from smaller algorithms whose behavior is already known and trusted. If you have a reliable max finder, you already trust that it checks every number in a list and returns the largest. Starting there saves work: you don't have to reinvent the logic for scanning a list, and you don't introduce new bugs into a part that already works. You only have to think hard about the new part.
Combination can mean chaining pieces together or modifying one for a new purpose. A max finder plus a swap, repeated, becomes selection sort: find the largest remaining value, swap it into place, repeat on a shrinking list. A sum algorithm becomes an average algorithm by adding one new step, a count of how many numbers were added, then dividing the sum by that count at the end. A max finder plus a MOD test becomes a largest-even-number finder: check each number with MOD 2 to filter for evens, then run the max logic on just those.
This matters because Big Idea 3 is built on the idea that variables, loops, and procedures are reusable building blocks, not one-off tricks. Once an algorithm is trusted, it becomes a unit you can call on inside something bigger, the same way a procedure call hides its own steps. But assembly is not automatic safety: the old pieces being correct does not mean the new combination is correct, which is why testing comes back into the picture even for proven parts.
Key terms
- Max finder
- An algorithm that scans a list and keeps track of the largest value seen so far.
- MOD test
- A check using the remainder operation, MOD 2, to determine whether a number is even or odd.
- Selection sort
- A sorting algorithm built from repeatedly finding the maximum of the unsorted portion and swapping it into place.
- Combining logic
- The new code that connects two trusted algorithms together, such as the order of operations when merging their results.
Watch it explained
- How it worksHow does combining a maximum finder with a swap turn into a sorting algorithm?
- How it worksWalk me through modifying a sum algorithm into an average algorithm.
- Worked exampleShow me building a routine for the largest even number out of a max finder and a MOD test.
- Going furtherWhat changes about testing when a new algorithm is assembled from already tested pieces?
Check yourself
End of topic.