Skip to content
Ameen Abozaid
PublishedBEG-017-L01

What an algorithm is

  • Lesson 1 of 7
  • 11 min read
  • Beginner
On This Lesson 11 topics

Lesson Overview

You have learned to write programs with decisions, loops, methods, and arrays, and you have learned to plan before coding. This module puts those skills to work on the most classic problems in programming: finding a value in a list and putting a list in order.

First we need a word for what we are about to do. An algorithm is a clear, finite list of steps that solves a problem. You have been writing algorithms already: the pseudocode and hand traces from the planning module were algorithms, and so is every method you have written. What is new is the idea that one problem can have several algorithms, and that we can compare them.

Why this matters: backend systems search and sort constantly (find a customer, order a list of products by price). Choosing a method that needs a thousand steps instead of ten is the difference between a fast service and a slow one. Junior interviews also ask about searching and sorting very often.

This lesson builds on arrays, loops, and methods (modules on loops, methods, and arrays) and on the plan-first habits from the problem-solving module.

Learning Objectives

By the end of this lesson you will be able to:

  • Define an algorithm as a clear, finite list of steps that solves a problem.
  • Give an everyday example of an algorithm and say which parts of it are the input and the output.
  • Explain why two different algorithms can solve the same problem.
  • State the order in which we judge an algorithm: correct first, then how many steps it takes.
  • Write a small algorithm as a Java method and test it on normal and edge-case input.
  • Name the two classic problems of this module: searching and sorting.

Written Explanation

An algorithm is a recipe

A recipe takes ingredients (input), follows steps in a fixed order, and produces a dish (output). An algorithm is the same shape:

  • It has input: the data it starts with.
  • It has steps that are clear and unambiguous. "Add some salt" is not clear enough for a computer; "add 2 to the counter" is.
  • It has output: the answer.
  • It finishes: after a limited number of steps it stops.

The pseudocode you wrote earlier is an algorithm written for people. A Java method is the same algorithm written for the computer. The method largest(int[] a) that returns the biggest number of an array is a good small example. In words:

  1. Remember the first number as the best so far.
  2. Look at each remaining number in turn.
  3. If it is bigger than the best so far, make it the new best.
  4. When the numbers run out, the best so far is the answer.

Many algorithms, one problem

Suppose a class list is in alphabetical order and you want to find "Mona".

  • Way 1: read from the top. Check the first name, then the second, and so on, until you find her or run out of names.
  • Way 2: open in the middle. Look at the middle name. If it comes after "Mona" in the alphabet, Mona must be in the first half, so ignore the second half. Repeat with the half that is left.

Both ways find Mona. They are two different algorithms for the same problem. Way 1 works on any list. Way 2 is much faster on a long list, but it only works because the list is sorted. You will write both in the next two lessons.

The same is true for putting books on a shelf by height. You could repeatedly swap neighbours that are in the wrong order, or repeatedly pick the shortest remaining book and place it next. Different steps, same result.

How we compare algorithms

When two algorithms exist, which one is better? We ask two questions, in this order:

  1. Is it correct? Does it give the right answer for every valid input, including the awkward ones (an empty array, one element, a target that is not there)? A fast algorithm that is sometimes wrong is useless.
  2. How many steps does it take? For a small list the difference does not matter. For large lists it matters a great deal. We will measure this by counting steps, such as comparisons, and later by timing.

Other qualities exist (how easy the code is to read, how much memory it needs), and readability matters in real teams. In this module we focus on correctness and the number of steps.

Searching and sorting

Two problems appear everywhere, so they are the classic starting point:

ProblemQuestionExample
SearchingIs this value in the collection, and where?Find the order with id 1093.
SortingPut the collection in order.List products from cheapest to dearest.

Sorting and searching are linked: a sorted collection can be searched much faster, which is why a book index, a phone book, and a dictionary are all in order.

Writing an algorithm as a method

Turning an algorithm into code follows the habits you already have: understand the problem, write the steps, then code, then test the edge cases. Here is largest and a second algorithm, isSorted, which we will reuse in this module to check that our sorting code works.

java
static int largest(int[] a) {
    int best = a[0];
    for (int i = 1; i < a.length; i++) {
        if (a[i] > best) best = a[i];
    }
    return best;
}

static boolean isSorted(int[] a) {
    for (int i = 0; i + 1 < a.length; i++) {
        if (a[i] > a[i + 1]) return false;
    }
    return true;
}

Notice that largest starts with a[0]. That is fine for an array with at least one element, but an empty array has no a[0] and the program would fail with an ArrayIndexOutOfBoundsException. A correct algorithm states what input it accepts; here, "at least one element". isSorted has no such problem: for an empty array or a one-element array the loop body never runs and the method returns true, which is the right answer (nothing is out of order).

Examples

Example 1: finding the largest mark (simple)

java
int[] marks = {62, 91, 48, 77};
System.out.println(largest(marks));

Output:

text
91

Trace with the variable table from the planning module:

stepia[i]best
start--62
119191
224891
337791

Every element is looked at once, so an array of 4 numbers needs 3 comparisons after the start, and an array of 4,000 needs 3,999. The work grows in step with the data. Remember this: it is the first example of counting steps.

Example 2: two algorithms for "Mona" (practical)

The list is {"Adam", "Dina", "Hassan", "Layla", "Mona", "Omar", "Sara"}. Reading from the top with a counter:

java
int checks = 0, found = -1;
for (int i = 0; i < names.length; i++) {
    checks++;
    if (names[i].equals("Mona")) { found = i; break; }
}
System.out.println("top-down: index " + found + " after " + checks + " checks");

Output:

text
top-down: index 4 after 5 checks

Opening in the middle (names are numbered 0 to 6):

  1. Middle is index 3, "Layla". "Mona" comes after "Layla", so the answer is in indexes 4 to 6.
  2. Middle of those is index 5, "Omar". "Mona" comes before "Omar", so the answer is in index 4 only.
  3. Index 4 is "Mona". Found after 3 looks.

Three looks instead of five. For 7 names the saving is small; for a million names it is enormous, as the next lessons show.

Example 3: checking the work with isSorted (realistic)

Professionals do not trust an algorithm they have not tested. A small checking method is a normal tool. We run isSorted on three cases:

java
System.out.println(isSorted(new int[]{2, 5, 9}));
System.out.println(isSorted(new int[]{2, 9, 5}));
System.out.println(isSorted(new int[]{}));

Output:

text
true
false
true

The third case is the edge case. When we write sorting algorithms later, we will run isSorted on the result, on an empty array, and on a one-element array. This is the same "test the edge cases" habit from the planning module, now applied to algorithms.

Backend Insight

Almost every backend feature is an algorithm underneath: find the user with this email, return the 20 newest orders, list items by price. In real services you will usually call a ready-made, well-tested method from the Java library or a database (for example Arrays.sort), not write a search yourself. Understanding the algorithm still pays off:

  • You can predict why a request becomes slow when the data grows.
  • You can tell when a database needs an index (a sorted structure that makes searches fast) instead of scanning every row.
  • You can read other people's code and spot an accidental slow loop.

Interviewers ask about searching and sorting because they reveal whether you can reason step by step. A later module formalises the comparison of step counts; this module gives you the intuition.

Common Mistakes

Mistake 1: Thinking a faster algorithm is always better

  • Incorrect: "Binary search is faster, so I will always use it."
  • Correct: "Binary search is faster when the data is sorted. On unsorted data it is wrong. Correctness comes first."

Mistake 2: Writing steps that are not clear

  • Incorrect: "Find the good ones."
  • Correct: "For each mark, if it is at least 50, add one to the counter."

If a step could mean two things, it is not yet an algorithm.

Mistake 3: Forgetting the edge cases

An algorithm that works for {62, 91, 48, 77} can still fail on an empty array. Always ask: what if the array is empty, has one element, or contains repeated values?

Mistake 4: Judging by feel instead of by counting

"It feels fast on my small test" says nothing about a million items. We compare algorithms by counting steps as the input grows.

Exercises

Try each exercise yourself before opening the solutions.

Level A: Foundation

A1. In your own words, define "algorithm" in one sentence.

Show solution A1

A1. An algorithm is a clear, finite list of steps that takes some input and solves a problem.

A2. Name the input and the output of the algorithm "find the largest number in an array".

Show solution A2

A2. Input: the array of numbers. Output: the single largest number.

A3. True or false: if two algorithms solve the same problem correctly, they always take the same number of steps.

Show solution A3

A3. False. Different algorithms can need very different numbers of steps. Reading from the top and opening in the middle both find a name, but the second needs far fewer looks on a long sorted list.

Level B: Application

B1. Write a method static int countAbove(int[] a, int limit) that returns how many elements are greater than limit. What does it return for an empty array?

Show solution B1

B1.

java
static int countAbove(int[] a, int limit) {
    int count = 0;
    for (int v : a) {
        if (v > limit) count++;
    }
    return count;
}

For an empty array the loop does not run, so it returns 0. Run on {62, 91, 48, 77} with limit 60 it returns 3.

B2. Trace largest on {3, 9, 4, 12, 7} with a variable table (columns i, a[i], best).

Show solution B2

B2.

stepia[i]best
start--3
1199
2249
331212
44712

The answer is 12.

B3. Write the "open in the middle" idea as four or five numbered steps for finding a word in a printed dictionary. Which property of the dictionary makes it work?

Show solution B3

B3. 1. Open the dictionary near the middle. 2. Compare the word on the page with your word. 3. If your word comes earlier in the alphabet, keep only the front half; if later, keep only the back half. 4. Repeat with the half you kept until you find the page. It works because the words are in alphabetical order, so you know which half cannot contain your word.

Level C: Challenge

C1. largest fails on an empty array. Describe two different ways to deal with this (one that changes the method, one that does not) and say which you prefer.

Show solution C1

C1. Option one: change the method, for example check a.length == 0 first and throw an IllegalArgumentException (or return a chosen value). Option two: leave the method alone and document that callers must pass at least one element, checking before they call. Preferring the first is reasonable because the method then fails clearly and early, whoever calls it. Either answer is fine if you explain the reason.

C2. Write an algorithm (pseudocode is enough) that returns true if an array contains any repeated value. Say how many comparisons it needs for 5 elements if you compare every pair once.

Show solution C2

C2. For each position i, compare a[i] with every later element a[j]; if any pair is equal, return true; after all pairs, return false. With 5 elements the pairs are 4 + 3 + 2 + 1 = 10 comparisons.

Mini Challenge

Choose a task you do by hand, such as finding a contact in your phone or tidying a row of books. Write its algorithm as numbered steps that someone else could follow without asking you questions. Then answer: what is the input, what is the output, and does the algorithm always finish? Finally, invent an unusual input (an empty list, two identical items) and check that your steps still give a sensible result.

Check your work: every step is clear and unambiguous, and you tested at least one edge case.

Summary & Next Lesson

Key takeaways

  • An algorithm is a clear, finite list of steps that turns input into output and solves a problem.
  • One problem can have several algorithms. We judge them by correctness first, then by how many steps they take.
  • Searching (find a value) and sorting (put values in order) are the classic problems, and they are linked: sorted data can be searched faster.
  • A Java method is an algorithm written for the computer. Test it on normal input and on edge cases such as the empty array.
  • Counting steps, not feeling, is how we compare algorithms.

Next lesson

The next lesson, "Linear search", writes the first of the two ways to find "Mona": check each element in order until you find the target or run out of elements.

Self-check

  1. What three things does every algorithm have (input, steps, and what else)?
  2. Which do we ask first about an algorithm: how fast, or is it correct?
  3. Name the two classic problems of this module.
  4. Why does largest fail on an empty array?
  5. Why can "open in the middle" find a name faster than "read from the top"?
Show answers
  1. Output (and it must finish after a limited number of steps).
  2. Is it correct.
  3. Searching and sorting.
  4. It starts with a[0], which does not exist in an empty array, so it throws an ArrayIndexOutOfBoundsException.
  5. It throws away half of the remaining names at every look, which only works because the list is in alphabetical order.

References

  • Oracle, Arrays (Java SE 21 API). Shows that the standard library already provides tested sorting and searching methods (the Backend Insight statement), including binarySearch, which requires a sorted array.
  • The definition of an algorithm used here, the recipe analogy, and the comparison order (correct first, then steps) are this course's own teaching framing. All Java code in this lesson was compiled and run on JDK 21 and the outputs shown are the real outputs.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.