What is an Algorithm in Programming? Explained with Examples

Before you write a single line of code, you need a plan.

Think about it. When you follow a recipe, you do not just throw ingredients together and hope for the best. You follow steps. In order. Every time. That is exactly what an algorithm is — a clear, step by step plan that tells your program what to do and how to do it.

In this guide, you will learn what algorithms are, how they work, and why every program ever built — from Google Maps to YouTube recommendations — starts with one.

core concept

What is an algorithm?

Before you write a single line of code, you need a plan. That plan — in programming — is called an algorithm.

simple definition

A step-by-step plan to solve a problem

An algorithm is a set of clear, ordered steps that solve a problem or complete a task. It’s not code — it’s the thinking behind the code. You can write an algorithm in plain English, and it will work in any programming language.

I used to jump straight into writing code with no plan. My programs were a mess. The day I started writing algorithms first, everything became cleaner and faster.

step 1 → step 2 → step 3 → result
real-life analogy

Recipe, GPS & morning routine

You follow algorithms every single day — you just don’t call them that. Every one of these is a set of ordered steps that gives you a predictable result.

📚
Recipe
1. Boil water
2. Add pasta
3. Drain
4. Serve
🌍
GPS
1. Find location
2. Plot route
3. Turn left
4. Arrive
☼
Morning routine
1. Wake up
2. Brush teeth
3. Get dressed
4. Leave
key difference

Algorithm vs code — what’s the difference?

An algorithm is the plan. Code is the implementation of that plan in a specific language. The same algorithm can be written in Python, JavaScript, Java — or even plain English.

algorithm
Language-independent plan
Written in plain English or pseudocode. Works in any language.
1. Get two numbers
2. Add them
3. Print result
code
Language-specific implementation
Written in Python, JS, etc. Only runs in that language.
a = int(input())
b = int(input())
print(a + b)
properties

Properties of a
good algorithm

Any set of steps can be called an algorithm — but a good algorithm has four specific properties that make it reliable, predictable, and efficient.

1
property 01
📝

Clear and unambiguous steps

Every step must be precise and leave no room for interpretation. “Sort the list” is vague. “Compare adjacent items and swap if left is bigger” is clear. Ambiguous steps cause unpredictable results.

✓ clear instruction
2
property 02
🏳

Has a starting and ending point

A good algorithm must start somewhere and finish somewhere. An algorithm that runs forever is a bug — not a feature. Every algorithm needs a defined beginning and a clear stopping condition.

start → … → end
3
property 03
⚙️

Same output for same input

Give it the same input twice — you must get the same result both times. Algorithms are deterministic. If you get different answers from the same input, something in the logic is broken.

input(5) → always 25
4
property 04
⚡

Efficient — no wasted time or memory

A good algorithm uses the least number of steps and memory needed to solve the problem. Two algorithms can give the same answer — but one might take seconds while the other takes hours on large data.

fewer steps = faster
all 4:
✓ clear steps ✓ start + end ✓ deterministic ✓ efficient
step-by-step

How to write an
algorithm (step by step)

Writing an algorithm is a skill you can learn in three simple steps. Follow this process for any problem — big or small.

1
step 1

Understand the problem

Before writing anything, make sure you fully understand what you need to do. Ask yourself: what are the inputs? What should the output be? What are the rules? Jumping to a solution without this causes bugs every time.

  • What data goes in?
  • What result should come out?
  • Are there any edge cases?
2
step 2

Write the steps in plain English

Write your solution in plain language — no code needed yet. Just list every step the computer needs to take to solve the problem. This forces you to think through the logic before worrying about syntax.

3
step 3

Turn it into pseudocode

Pseudocode is code-like writing that no computer can run. It bridges plain English and real code — using if, for, and print keywords but without strict syntax. Any language can then implement it.

START Get three numbers: a, b, c SET largest = a IF b > largest → largest = b IF c > largest → largest = c Print largest END
real example

Find the largest number — all 3 stages

Watch how the same problem evolves from plain English → pseudocode → real Python:

plain english
1. Take 3 numbers 2. Compare each pair 3. Remember biggest 4. Print the winner
pseudocode
SET largest = a IF b > largest largest = b IF c > largest largest = c PRINT largest
Python code
a,b,c = 4,9,2 largest = a if b > largest: largest = b if c > largest: largest = c print(largest)
algorithm types

Types of algorithms every
beginner should know

Thousands of algorithms exist — but as a beginner, you only need to know three types. Master these and you’ll handle most real-world problems.

type 01 🔍 Searching algorithms

Searching algorithms find a specific item inside a collection of data. They answer the question: “Is this value here — and if so, where?” Used in search bars, databases, and autocomplete features every day.

examples
  • Linear Search
  • Binary Search
  • Depth-First Search
type 02 📉 Sorting algorithms

Sorting algorithms arrange data in a specific order — smallest to largest, A to Z, or any other rule. Used whenever you filter products by price, sort a playlist, or display results by date.

examples
  • Bubble Sort
  • Selection Sort
  • Merge Sort
type 03 🔄 Recursive algorithms

A recursive algorithm calls itself to solve a smaller version of the same problem. It breaks big problems into smaller identical pieces until it reaches a base case it can solve directly — then builds back up.

examples
  • Factorial (n!)
  • Fibonacci
  • Tower of Hanoi
typewhat it doesbeginner exampleused for
🔍 SearchingFinds an item in dataLinear SearchSearch bars, databases
📉 SortingArranges data in orderBubble SortFilters, playlists, rankings
🔄 RecursiveCalls itself to solve sub-problemsFactorialMath, trees, file systems
🔍 linear search

Linear search — the
simplest search algorithm

Start at the beginning, check every item one by one. If you find it — done. If you reach the end — it’s not there. That’s the entire algorithm.

how it works

How linear search works

Linear search goes through a list from the very first item to the last, comparing each one to the value you’re looking for. No skipping, no shortcuts — just a straight line, one check at a time.

It’s the most natural search — the same way you’d look for a name in a handwritten list. Simple, reliable, and easy to code from scratch.

walkthrough

Step-by-step — find the number 7

Array: [3, 1, 7, 9, 4] — looking for 7

1Check index 0 → 3 ≠ 7 → skip
2Check index 1 → 1 ≠ 7 → skip
3Check index 2 → 7 = 7 → Found at index 2 ✓ Stop!

The loop checks each index — when it finds a match it returns the position immediately. If nothing matches, it returns -1.

linearSearch.js
function linearSearch(arr, target) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === target) {
      return i;  // found! return index
    }
  }
  return -1;  // not found
}

console.log(linearSearch([3,1,7,9,4], 7));
output →2 (found at index 2)

Python’s enumerate() gives both index and value — cleaner and more readable than a manual counter.

linear_search.py
def linear_search(arr, target):
    for i, val in enumerate(arr):
        if val == target:
            return i    # found!
    return -1          # not found

print(linear_search([3,1,7,9,4], 7))
output →2 (found at index 2)
binary search

Binary search —
the faster way to search

Instead of checking every item, binary search cuts the list in half each time. It’s like opening a dictionary to the middle instead of reading page by page.

how it works

How binary search works

Binary search only works on sorted data. It finds the middle item, compares it to the target, then cuts half the list out instantly. It keeps halving until it finds the value — or determines it’s not there.

Step 1 — Find middle (index 3 = 5). Target is 7. 7 > 5 → search right half
1
3
5
5
7
9
11
left half eliminated instantly — 3 items skipped
Step 2 — New middle = 9. 7 < 9 → search left. Next check = 7 → Found ✓
1
3
5
5
7
9
11
found in just 2 checks — linear would take 5 ✓
why it’s faster

Why binary search beats linear search

With 1,000 items, linear search checks up to 1,000 times. Binary search needs at most 10 checks — because it halves the search space every single step. That gap gets huge with bigger data.

🔍 Linear search
1,000
max checks for 1,000 items
⚡ Binary search
10
max checks for 1,000 items
⚠ Requirement: the list must be sorted first before binary search can work

The while loop keeps running as long as left ≤ right. Each pass finds the midpoint and eliminates half the remaining array.

binarySearch.js
function binarySearch(arr, target) {
  let left = 0, right = arr.length - 1;

  while (left <= right) {
    let mid = Math.floor((left + right) / 2);
    if (arr[mid] === target) return mid;
    if (arr[mid] < target)   left  = mid + 1;
    else                    right = mid - 1;
  }
  return -1;
}

console.log(binarySearch([1,3,5,7,9,11], 7));
output →3 (found at index 3)

Same logic in Python — integer division // handles the midpoint cleanly.

binary_search.py
def binary_search(arr, target):
    left, right = 0, len(arr) - 1

    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target: return mid
        elif arr[mid] < target: left  = mid + 1
        else:                  right = mid - 1
    return -1

print(binary_search([1,3,5,7,9,11], 7))
output →3 (found at index 3)
bubble sort

Bubble sort — the
beginner’s sorting algorithm

Compare two neighbors, swap if they’re in the wrong order, repeat. That’s all bubble sort does — and it’s the perfect place to start learning sorting.

how it works

How bubble sort works

Bubble sort compares two adjacent items in the array and swaps them if the left one is bigger. It repeats this across the whole list — again and again — until no more swaps are needed. Larger values “bubble up” to the end with each pass.

1
smallest
3
5
7
9
largest ↑
step-by-step

Sorting [5, 3, 8, 1] — pass by pass

Each pass moves the largest unsorted value to its final position. Yellow = being compared, green = sorted and done.

start
5
3
8
1
pass 1
3
5
1
8
8 bubbled to end ✓
pass 2
3
1
5
8
5 settled ✓
pass 3
1
3
5
8
all sorted ✓

Two nested loops: outer counts passes, inner does the comparisons. The inner loop shrinks each pass since the last item is already sorted.

bubbleSort.js
function bubbleSort(arr) {
  let n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    for (let j = 0; j < n - i - 1; j++) {
      if (arr[j] > arr[j+1]) {
        [arr[j], arr[j+1]] = [arr[j+1], arr[j]];
      }
    }
  }
  return arr;
}
console.log(bubbleSort([5,3,8,1]));
output →[1, 3, 5, 8]

Same two-loop structure in Python. The inner loop shrinks by i each pass — no need to re-check already-sorted end items.

bubble_sort.py
def bubble_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        for j in range(n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
    return arr

print(bubble_sort([5, 3, 8, 1]))
output →[1, 3, 5, 8]
big O

Big O notation —
how we measure speed

Writing code that works is step one. Writing code that’s fast enough is step two. Big O is how developers measure and compare algorithm speed.

definition

What is Big O notation?

Big O tells you how the number of steps grows as your data gets bigger. It doesn’t measure exact seconds — it measures how an algorithm scales. A fast algorithm on 10 items might be devastatingly slow on 10 million.

O(1) — constant O(n) — linear O(n²) — quadratic
O(1) Constant time — always one step fastest

No matter how big the array, it takes exactly one step. Accessing an array by index is O(1) — the size doesn’t matter.

e.g. arr[0] — always instant

steps for n items
n=10 → 1 step
n=1000 → 1 step
O(n) Linear time — grows with input acceptable

Steps grow proportionally with data size. 10 items = 10 steps. 1000 items = 1000 steps. Linear search is O(n).

e.g. loop through array

steps for n items
n=10 → 10 steps
n=1000 → 1000 steps
O(n²) Quadratic — grows very fast slow on big data

Steps grow as the square of the input size. 10 items = 100 steps. 100 items = 10,000 steps. Bubble sort is O(n²).

e.g. nested loops

steps for n items
n=10 → 100 steps
n=100 → 10,000 steps
notationnamen=10n=1,000speed
O(1)Constant1 step1 step⚡ fastest
O(n)Linear10 steps1,000 steps🕐 ok
O(n²)Quadratic100 steps1,000,000 steps🐢 slow
faq 04

FAQs about
algorithms

Quick answers to the four questions beginners ask most about algorithms.

Q1 What is an algorithm in simple words? +
definition

An algorithm is a step-by-step plan for solving a problem — before you write any code. Think of it like a recipe: a set of clear, ordered instructions that always gives the same result when followed correctly.

step 1 → step 2 → step 3 → result
Q2 What is the difference between algorithm and pseudocode? +
comparison

An algorithm is the logical plan — it can be written in plain English. Pseudocode is that same plan written in a code-like style using keywords like IF, FOR, and PRINT — closer to real code but still language-independent.

algorithm
Plain English steps. “Find the largest number in the list.”
pseudocode
IF a > b THEN SET max = a ELSE SET max = b
Q3 What is the fastest sorting algorithm? +
sorting speed

It depends on the data — but Merge Sort and Quick Sort are among the fastest for general use, both running at O(n log n). Bubble Sort is the slowest at O(n²) — only good for learning, not real projects.

Quick SortO(n log n) — fast ✓
Merge SortO(n log n) — fast ✓
Insertion SortO(n²) — ok for small data
Bubble SortO(n²) — slowest ✗
Q4 Why do beginners need to learn algorithms? +
why it matters

Algorithms teach you how to think before you code — the most valuable skill in programming. They also come up in every job interview, help you write faster programs, and build the logical thinking all developers need.

  • Essential for technical interviews at every company
  • Makes your programs faster and more efficient
  • Builds logical thinking that transfers to any language