What Is an Algorithm in Programming?

Published on: July 10, 2026
Reading time: 6 minutes
Ilustração que representa um algoritmo

An algorithm in programming is a finite and ordered set of steps that transforms input into a result. It describes how to solve a problem before a specific programming language handles the details. Searching for a name, sorting prices, validating a password, calculating a route, and recommending a product all depend on algorithms.

This guide explains algorithms through everyday examples, pseudocode, flowcharts, and Python code. It also introduces correctness, efficiency, edge cases, testing, and a practical method for designing solutions.

Algorithm meaning

The National Institute of Standards and Technology defines an algorithm in its Dictionary of Algorithms and Data Structures as a computable set of steps for achieving a desired result. In simpler language, an algorithm is a precise recipe that another person or computer can follow.

An algorithm is not the same as source code. The algorithm is the method; the code is one implementation of that method. The same sorting algorithm can be written in Python, Java, JavaScript, or another language.

Everyday algorithm example

Consider making tea:

  1. Fill the kettle with water.
  2. Heat the water.
  3. Place tea in a cup.
  4. Pour hot water into the cup.
  5. Wait for a defined time.
  6. Remove the tea and serve.

The sequence has input, ordered actions, conditions, and an output. Ambiguous instructions such as “wait a while” are acceptable for a person but poor for a computer. A program needs a measurable rule, such as “wait four minutes.”

Properties of a useful algorithm

  • Clear: each step has one understandable meaning.
  • Finite: it eventually stops.
  • Correct: it produces the expected result for valid input.
  • Defined: inputs, outputs, and assumptions are known.
  • Effective: each operation can actually be performed.
  • General: it solves a class of related cases, not only one hard-coded example.

A correct algorithm can still be inefficient. A fast algorithm can still be wrong for an edge case. Good software considers both correctness and resource use.

Input, processing, and output

Many beginner algorithms can be described with three parts:

  • Input: data received from a user, file, sensor, API, or another function.
  • Processing: calculations, comparisons, repetitions, and transformations.
  • Output: a displayed value, returned result, changed record, file, or action.

For example, a temperature converter receives Celsius as input, applies a formula, and returns Fahrenheit as output.

Write pseudocode first

Pseudocode expresses logic without the strict syntax of a programming language:

READ price
READ discount_percentage

IF price is negative
    DISPLAY error
ELSE IF discount_percentage is outside 0 to 100
    DISPLAY error
ELSE
    discount = price * discount_percentage / 100
    final_price = price - discount
    DISPLAY final_price
END IF

Pseudocode helps you focus on decisions and sequence before dealing with parentheses, indentation, imports, or data types. It is not executed by Python.

Translate pseudocode into Python

def calculate_final_price(price: float, discount_percentage: float) -> float:
    if price < 0:
        raise ValueError("price cannot be negative")
    if not 0 <= discount_percentage <= 100:
        raise ValueError("discount must be between 0 and 100")

    discount = price * discount_percentage / 100
    return price - discount


print(calculate_final_price(200, 15))

The programming logic with Python guide explains variables, conditions, loops, functions, and validation in more detail.

Represent an algorithm with a flowchart

A flowchart uses standard shapes to show execution:

  • oval for start or end;
  • parallelogram for input or output;
  • rectangle for processing;
  • diamond for a decision;
  • arrows for control flow.

Flowcharts are useful when a process contains several branches or when technical and nontechnical participants need to discuss the same workflow. For very large systems, diagrams should remain high-level; trying to draw every line of code makes them unreadable.

Sequence, selection, and repetition

Most algorithms combine three fundamental control structures.

Sequence

Steps run in order:

subtotal = 100
shipping = 12
total = subtotal + shipping
print(total)

Selection

A condition chooses a branch:

age = 20

if age >= 18:
    print("Adult")
else:
    print("Minor")

These structures are covered in the Academify material on Python if, elif, and else.

Repetition

A loop repeats an operation:

total = 0

for number in range(1, 6):
    total += number

print(total)

See the Python loops guide and the dedicated range() guide for iteration patterns.

Example: find the largest number

Problem: given a nonempty list, find its largest value without calling max().

Pseudocode

SET largest to first value
FOR each remaining value
    IF value is greater than largest
        SET largest to value
RETURN largest

Python implementation

def find_largest(numbers):
    if not numbers:
        raise ValueError("numbers cannot be empty")

    largest = numbers[0]

    for number in numbers[1:]:
        if number > largest:
            largest = number

    return largest

The empty-list check is an edge case. Without it, accessing numbers[0] raises an IndexError. The exception handling guide explains how functions can signal invalid input clearly.

Linear search checks items one by one until it finds the target:

def linear_search(items, target):
    for index, item in enumerate(items):
        if item == target:
            return index
    return None

If the target is first, the result is immediate. If it is absent, every item is checked. This method works on unsorted data and is often sufficient for small collections.

Binary search repeatedly eliminates half of a sorted sequence:

def binary_search(sorted_items, target):
    low = 0
    high = len(sorted_items) - 1

    while low <= high:
        middle = (low + high) // 2
        value = sorted_items[middle]

        if value == target:
            return middle
        if value < target:
            low = middle + 1
        else:
            high = middle - 1

    return None

Binary search is much faster for repeated searches on large sorted data, but the sorting requirement matters. Applying it to unsorted values produces unreliable results.

Correctness and edge cases

To reason about correctness, ask:

  • What happens with the smallest allowed input?
  • What happens with empty input?
  • Are duplicates allowed?
  • Can values be negative or missing?
  • Does the algorithm terminate?
  • What invariant remains true after every loop iteration?
  • Does the result satisfy the original requirement?

Writing examples before implementation often exposes ambiguous requirements.

Test an algorithm

def test_linear_search_finds_first_match():
    assert linear_search([4, 8, 8, 10], 8) == 1


def test_linear_search_returns_none_when_missing():
    assert linear_search([4, 8, 10], 7) is None

Automated tests check normal cases, boundaries, invalid input, and regressions. The Pytest beginner guide explains test discovery and assertions.

Time complexity

Time complexity describes how the amount of work grows as input size grows. It does not measure exact seconds. Common growth classes include:

  • O(1): constant work, such as reading one list position.
  • O(log n): repeatedly reducing the search space, as in binary search.
  • O(n): examining each item once, as in linear search.
  • O(n log n): common efficient comparison-sorting behavior.
  • O(n²): nested comparisons over the same growing collection.

The exact implementation, data structure, and input characteristics still matter. Complexity is a tool for comparing growth, not a complete performance guarantee.

Space complexity

An algorithm may trade memory for speed. Creating a set from a list uses extra memory but can make repeated membership checks faster:

allowed_ids = set([101, 203, 407, 509])

if 407 in allowed_ids:
    print("Allowed")

The Python sets guide explains unique values and efficient membership tests.

Choose the right data structure

Algorithm quality depends on data representation. A dictionary provides direct key lookup, a set handles uniqueness and membership, a queue models first-in-first-out processing, and a stack models last-in-first-out behavior. The Python collection comparison helps choose among common built-in structures.

A practical algorithm-design process

  1. Define the problem: state the desired result and constraints.
  2. List inputs and outputs: include types, ranges, and invalid values.
  3. Work through examples manually: include ordinary and edge cases.
  4. Choose data structures: match the operations the algorithm needs.
  5. Write pseudocode: express the logic without syntax distractions.
  6. Check termination and correctness: ensure loops progress and branches cover all cases.
  7. Implement a clear version: prefer correctness and readability first.
  8. Test: automate representative cases.
  9. Measure: profile real bottlenecks before optimizing.
  10. Document assumptions: explain requirements that are not obvious.

Common beginner mistakes

  • Coding before understanding the problem: unclear requirements produce repeated rewrites.
  • Ignoring invalid input: decide whether to reject, normalize, or skip it.
  • Forgetting loop progress: a condition can remain true forever.
  • Optimizing too early: a complicated solution may be harder to verify and no faster for real data.
  • Testing only one example: one successful output does not prove correctness.
  • Confusing syntax knowledge with problem solving: knowing Python commands does not automatically reveal the right method.

Practice project: calculate an average with validation

Pseudocode

READ a list of grades
IF the list is empty
    REPORT an error
FOR every grade
    IF grade is outside 0 to 100
        REPORT an error
RETURN sum of grades divided by quantity

Python

def calculate_average(grades):
    if not grades:
        raise ValueError("at least one grade is required")

    for grade in grades:
        if not 0 <= grade <= 100:
            raise ValueError(f"invalid grade: {grade}")

    return sum(grades) / len(grades)

This small algorithm has clear input, validation, processing, output, and failure rules. It can be tested independently from user input or a graphical interface.

Conclusion

An algorithm in programming is a precise method for transforming input into a result. Strong algorithms begin with a clear problem definition, handle edge cases, terminate, produce correct output, and use suitable resources. Practice by writing pseudocode, translating it into small Python functions, testing boundaries, and comparing alternative approaches before worrying about clever optimizations.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    Logo do Python com expressão pensativa e o texto range(), representando a função range no Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python range(): Complete Guide with Examples

    Learn Python range() with start, stop, step, negative values, loops, indexing patterns, performance, common mistakes, and practical beginner examples.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    texto 'operadores em Python' com os simbolos de operadores e o logo do Python à direita
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Operators: Types and Practical Examples

    Learn Python operators with arithmetic, comparison, assignment, logical, membership, identity, bitwise, set, and conditional examples, plus precedence and common mistakes.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    texto 'None' centralizado com um fundo com as cores do Pyton
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python None Explained: Meaning and Best Practices

    Learn what Python None means, how to compare it correctly, use optional returns and defaults, distinguish missing values, work with

    Ler mais

    Tempo de leitura: 6 minutos
    10/07/2026
    Ilustração representando conjuntos (sets) em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Sets: Complete Beginner Guide

    Learn Python sets from scratch: unique values, membership, add and remove methods, union, intersection, differences, subsets, comprehensions, frozenset, and practical

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Programador resolvendo problemas com Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Programming Logic with Python for Beginners

    Learn programming logic with Python using algorithms, pseudocode, input and output, conditions, loops, functions, data structures, validation, testing, and a

    Ler mais

    Tempo de leitura: 6 minutos
    10/07/2026
    Código Python com valores Boolean True e False em tela de computador
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Booleans: True, False, and Logic

    Learn Python booleans with True and False, comparison and logical operators, truthy and falsy values, identity, membership, short-circuiting, and validation.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026