1. Home
  2. Explore
  3. Computer Science
  4. Algorithms in Five Levels

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Algorithms in Five Levels

Algorithms: A Comprehensive Study Guide

Introduction: What is an Algorithm?

An algorithm is a set of step-by-step instructions for solving a problem or accomplishing a task. Algorithms are everywhere β€” not only in computers but in daily human routines. They represent an opportunity to solve problems, and the key to a good algorithm is precision: instructions must be clear, correct, and unambiguous.

Algorithm: A precise sequence of steps to solve a problem.

  • Algorithms are used in both the physical world and the virtual world.

  • Even simple daily activities (getting dressed, making a sandwich) can be broken into algorithms.

  • In computing, algorithms become code β€” instructions written in a programming language that a computer can execute.


πŸ§’ Level 1: Algorithms for a Child

What is a Computer?

A computer is an electronic device with a brain (the CPU or Central Processing Unit) that follows instructions, performs math (addition, subtraction), and responds to commands. Inside every computer there is:

  • CPU (Central Processing Unit): The hardware that executes instructions.

  • Memory (RAM): Random Access Memory β€” temporary storage for programs and games while they are being used. It forgets everything when the power goes out.

  • Storage (Hard Drive / Solid State Drive): Permanent storage for documents, high scores, and files. Data remains even after the computer is turned off.

Computer memory: RAM is like a desk where you work; the hard drive is like a filing cabinet where you store things permanently.

Algorithm Definition and Example

An algorithm is simply a list of instructions that tells someone (or a robot) what to do. For instance, a bedtime routine algorithm might be:

  1. Get dressed (into pajamas)

  2. Brush teeth

  3. Read a little story

  4. Go to bed

Precision in Instructions (The Peanut Butter Sandwich)

When giving instructions to a computer (or a robot), precision is critical. In a demonstration of making a peanut butter sandwich, imprecise instructions led to mistakes β€” e.g., taking all the bread out instead of one slice. An algorithm must be:

  • Exact: Every step must be specific.

  • Complete: No steps missing.

  • Unambiguous: Each step has only one interpretation.

Precision: Being very correct with instructions ensures the algorithm produces the desired result. In the digital world, imprecise algorithms can lead to wrong answers (e.g., searching on Google incorrectly).


πŸ§‘β€πŸŽ“ Level 2: Algorithms for a Teen

Everyday Algorithms

Even without using the fancy word, humans execute many algorithms daily:

  • Getting ready in the morning (brush teeth, brush hair, get dressed)

  • Following a recipe

  • Organizing contacts alphabetically on a phone

Algorithms in computing automate these step-by-step processes, often using a loop β€” a programming construct that repeats an action repeatedly.

Searching: Linear Search and Binary Search

A classic problem is finding a name (e.g., John) in a phone book. Three algorithms can be compared:

  • Linear Search: Start at the beginning and look at each page one by one. In the worst case, if the name is at the end, it takes N steps (where N is the number of pages). This is simple but slow.

  • Faster Linear Search (skip 2 pages at a time): Check two pages at once β€” this doubles speed but risks skipping over the target. It can be fixed by checking one extra page when the target might be between two pages. However, it's still linear time roughly.

  • Binary Search (Divide and Conquer):

    1. Go to the middle of the phone book.

    2. Determine if the target name is to the left or right (alphabetically).

    3. Tear the problem in half β€” discard the half that does not contain the name.

    4. Repeat on the remaining half.

Binary search: An algorithm that repeatedly cuts the search space in half, achieving logarithmic time.

Divide and Conquer

The technique used in binary search is called divide and conquer: take a big problem, break it into smaller pieces, solve each piece, and combine results. This approach leads to efficient algorithms.

Recursive Algorithms

A more sophisticated type of divide and conquer is a recursive algorithm: an algorithm that calls itself on a smaller version of the same problem. Recursion continues until the problem becomes so small it can be solved directly (the base case). For example:

  • Finding John in 1000 pages? Find the middle, then recursively search the appropriate half of 500 pages, then 250, and so on.

  • Recursion is powerful but requires careful design to avoid infinite loops.


πŸŽ“ Level 3: Algorithms for a College Student (Computer Science)

Sorting: Bubble Sort

Sorting is a fundamental algorithmic problem. Bubble sort is a simple sorting algorithm that repeatedly steps through a list, compares adjacent items, and swaps them if they are in the wrong order. It works like "bubbling" the largest unsorted element to the end.

Steps (sorting from smallest to largest):

  1. Compare the first two elements. If the first is larger than the second, swap them.

  2. Move to the next pair, compare and swap if needed. Continue to the end.

  3. After one pass, the largest element "bubbles" to the last position.

  4. Repeat the process for the remaining unsorted portion (excluding the last element already in place).

  5. Continue until no swaps are needed β€” the list is sorted.

Example with numbers [8, 1, 2, 6, 3, 7, 5, 4]:

  • Pass 1: 8 and 1 swap β†’ [1, 8, 2, 6, 3, 7, 5, 4]; then 8 and 2 swap β†’ [1, 2, 8, 6, 3, 7, 5, 4]; then 8 and 6 swap β†’ [1, 2, 6, 8, 3, 7, 5, 4]; then 8 and 3 swap β†’ [1, 2, 6, 3, 8, 7, 5, 4]; then 8 and 7 swap β†’ [1, 2, 6, 3, 7, 8, 5, 4]; then 8 and 5 swap β†’ [1, 2, 6, 3, 7, 5, 8, 4]; then 8 and 4 swap β†’ [1, 2, 6, 3, 7, 5, 4, 8]. Now 8 is in place.

  • Pass 2: only compare up to the 7th element (since 8 is done). Eventually 7 bubbles to place.

  • Continue until sorted: [1, 2, 3, 4, 5, 6, 7, 8]

Key points:

  • Bubble sort is simple but inefficient for large lists: O(n2)O(n^2)O(n2) time complexity.

  • It focuses on local problems β€” fixing adjacent inversions β€” rather than a global strategy.

  • Other sorting algorithms (merge sort, quicksort) are faster but conceptually more complex.

Algorithms in Social Media and Recommendations

  • Recommendation algorithms power platforms like TikTok, Netflix, and YouTube.

  • They observe user behavior (likes, saves, searches, watch time) to predict what content to show next.

  • The goal is engagement β€” the better the algorithm, the more time users spend, generating revenue.

  • These algorithms are not simple if-else rules written by programmers. Instead, they rely on machine learning and neural networks that learn patterns from vast amounts of data.

Machine Learning and Neural Networks

  • Machine learning: A subset of AI where algorithms learn from data without being explicitly programmed for every situation.

  • Neural networks: A type of machine learning inspired by the brain, consisting of layers of interconnected nodes (neurons). They take input (e.g., what you click on) and produce output (e.g., a recommendation).

  • The algorithm automatically adjusts internal weights based on training data to maximize performance (e.g., minimizing prediction error).

Key distinction: Traditional algorithms follow fixed rules; machine learning algorithms infer rules from data.


πŸ”¬ Level 4: Algorithms for a PhD Student (Research)

Researching and Inventing Algorithms

The most important part of algorithm research is thinking about inefficiencies and connecting threads between different problems. An algorithm is not just a way of doing something β€” it is about doing something efficiently.

  • Researchers analyze existing algorithms to find bottlenecks.

  • They invent new algorithms by combining ideas from different fields (e.g., using graph theory to speed up database searches).

  • A central goal is minimizing time and memory usage.

Learning Algorithms and Objective Functions

Learning algorithms (machine learning) are everywhere:

  • Google: Learns which articles and links are more valuable and re-ranks search results.

  • Recommender systems: Content feeds on social media, YouTube, Netflix β€” all driven by algorithms that learn from user interactions.

  • Deep fakes: Machine learning models learn to replicate voices, faces, and movements, generating synthetic media. This raises concerns about misuse.

All learning algorithms follow the same abstract pattern:

Input: Lots of data. Output: A model that optimizes an objective function (e.g., maximize engagement, minimize prediction error, win a game).

  • The objective function defines what the algorithm is trying to achieve.

  • In supervised learning, the objective might be to minimize the difference between predicted and actual labels.

  • In reinforcement learning, the objective is to maximize cumulative reward (e.g., winning a game).

Classical vs. Learned Game-Playing Algorithms

  • Classical algorithms (no AI): Examples include A search* β€” a pathfinding algorithm that systematically explores possibilities in a game state and picks the best move based on a heuristic. It does not learn from experience.

  • Learned agents (AI): AlphaZero, AlphaStar β€” they play millions of games and learn strategies from the data generated. They refine their play as they see more games.

  • The high-level abstraction is the same: input data, output an action. But the process differs:

    • Classical: hand-crafted rules and search.

    • Learned: neural networks trained on experience.

Ethical Concerns: Deep Fakes and Data Mining

  • Algorithmic advances bring risks: synthetic media (deep fakes) can misrepresent reality.

  • Vast amounts of personal data are being mined and analyzed to influence what we see and buy.

  • Algorithms can treat individuals as "just a pair of eyes with a wallet" rather than human beings.

  • There is a need to balance the positive potential of algorithms (better healthcare, transportation) with respect for privacy and autonomy.

Future of Algorithms

  • Algorithms will continue to encroach further into everyday life: routing trains, managing phones, optimizing logistics.

  • Data about individuals is everywhere, being mined and analyzed.

  • The challenge is to design algorithms that improve life without sacrificing human values.


πŸ‘©β€πŸ”¬ Level 5: Algorithms for an Expert (Data Scientist)

Algorithms in Data Science

Data science combines statistics, computer science, and domain knowledge to extract insights from data. Algorithms play a central role in two main areas:

  1. Optimization algorithms: Used in academia to find the best model or description of a dataset (e.g., gradient descent for training neural networks).

  2. Data products: In industry, algorithms become part of a product (e.g., personalization at the New York Times) that recommends content or automates decisions.

A data scientist must understand not only the algorithm's statistical performance but also:

  • Systems integration: How the algorithm receives reliable input and produces useful output.

  • Organizational integration: How a community of people (e.g., journalists) will use the algorithm in their workflow.

Large Language Models and Generative AI

  • Large language models (LLMs): A special case of generative AI, which in turn is a special case of machine learning. LLMs are trained on massive text corpora (encyclopedias, textbooks, web pages) to predict the next word (or token) in a sequence.

  • ChatGPT is a prominent example β€” a chatbot that uses an LLM plus fine-tuning for conversation.

  • Key terms:

    • Pre-training: The initial training of an LLM on a broad corpus.

    • Fine-tuning: Adapting the pre-trained model to a specific task or domain (e.g., conversations, programming help).

  • Both pre-training and fine-tuning are themselves training algorithms β€” they adjust the model's parameters to minimize prediction error.

People's perception of AI changed dramatically when they could directly interact with a high-quality chatbot (around November 2022). The underlying technology had existed for years, but the public now experiences it firsthand.

Understanding vs. Using Algorithms

  • Many modern algorithms (especially deep neural networks) work extremely well, yet researchers cannot fully explain why they work as they do.

  • This is a departure from older, deterministic algorithms where one could point to the exact line of code that produced a result.

  • The current state of LLM development has been likened to alchemy β€” practitioners try different designs (often in large companies) and see what works, without a complete theoretical foundation.

  • This is not entirely new; there are scientific precedents where algorithms work well before rigorous proofs exist. Sometimes proofs are later found to be flawed.

Is it problematic that we can't explain how they work?

  • It has risks: we may lose control or encounter unexpected behaviors.

  • However, algorithms and computational tools can be used productively without understanding every fundamental layer β€” just as one can drive a car without knowing organic chemistry.

  • Different levels of understanding exist along the "stack": you can use a high-level library like scikit-learn to do machine learning in seconds without knowing the optimization details underneath.

The Role of Fundamentals

Fundamental algorithms (binary search, linear search, bubble sort, selection sort, etc.) have been taught for decades. With powerful tools like ChatGPT that can sort numbers for you, do these fundamentals still matter?

  • Code and computation are a special case of technology.

  • You can use a car without understanding combustion, but for innovation and troubleshooting, deeper knowledge is valuable.

  • Similarly, understanding algorithm fundamentals enables you to:

    • Design better solutions.

    • Diagnose inefficiencies.

    • Innovate at a deeper level.

  • The fundamentals are loosely coupled to progress: advances often come from those who understand them, but the field also progresses through experimentation and empirical success.

Technology is Neither Good Nor Bad Nor Neutral

Kranzberg's First Law of Technology: Technology is neither good nor bad, nor is it neutral.

Every new piece of technology (algorithms included) has both positive and negative potential. We must actively think about its capabilities, the good it can do, and the possible harms.

  • Large language models can assist with writing, learning, and creativity β€” but also generate misinformation or deep fakes.

  • The same algorithm can be used for personalized healthcare or for manipulative advertising.

  • Ethical design, regulation, and public awareness are essential.


Conclusion: The Spectrum of Algorithms

Algorithms span from the most basic step-by-step instructions (making a sandwich) to the most advanced deep learning systems (generative AI). With each lesson and each algorithm studied, even the most advanced concepts become accessible. The journey from simple to complex is built on a foundation of precise thinking, iterative improvement, and an appreciation for efficiency. Whether in daily life or cutting-edge research, algorithms are a fundamental tool for solving problems β€” and the field continues to evolve, promising both opportunities and responsibilities.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent