跳到主要内容
英国伦敦 · 创立于 1994 年
中文

Unit 3: Data Structures and Algorithms

The common ways programs organise data in memory, the classic algorithms for searching and sorting, and how computer scientists compare the efficiency of different approaches.

Unit 3 of 5 · about 54 minutes

3.1 Organising data: common data structures

A data structure is a way of organising data in a computer so that it can be used efficiently. The choice of data structure affects how quickly a program can find, add, remove or sort information, and how much memory it uses. Choosing well is one of the most important decisions in software design, and it often matters more than clever code.

A helpful analogy is physical storage. A pile of papers is quick to add to but slow to search. A filing cabinet ordered alphabetically is slower to add to but quick to search. A queue at a counter serves people in the order they arrived. Each arrangement suits different tasks, and the same is true in software.

Arrays and lists

An array stores items one after another in a single block of memory, each identified by its position, or index. Because positions are numbered, the computer can jump straight to any item, for example the fifth customer in the list, very quickly. However, inserting an item in the middle means shifting everything after it along, which can be slow for large arrays. Many languages provide a flexible list that behaves like an array but grows automatically as items are added.

Linked lists

A linked list stores each item together with a reference, or pointer, to the next item. Items can sit anywhere in memory. Inserting or removing an item only requires changing a couple of references, but finding the hundredth item means following the chain from the start. Linked lists illustrate a recurring theme: improving one operation often makes another slower.

Stacks and queues

  • A stack works on a "last in, first out" basis, like a pile of plates. The most recently added item is the first removed. The undo feature in a word processor is a natural stack: the last change you made is the first one undone.
  • A queue works on a "first in, first out" basis, like people waiting at a counter. Print jobs, customer support tickets and messages waiting to be processed by a server are often managed as queues.

Hash tables (dictionaries)

A hash table, often called a dictionary or map, stores pairs of keys and values, such as a product code and its price, or a username and an account record. A mathematical function called a hash function turns each key into a position in memory, so the computer can usually find a value almost instantly without searching. This makes hash tables among the most widely used structures in practical programming. Their main limitation is that they do not keep items in any meaningful order.

Trees and graphs

A tree organises data hierarchically, with a single root and branches below it, like an organisation chart or the folders on a computer. A binary search tree keeps items in sorted order so that searching, adding and removing can all be reasonably fast. Databases use related tree structures to build indexes.

A graph is a set of items, called nodes, connected by links, called edges. Graphs model networks of all kinds: roads between towns, friendships in a social network, links between web pages and dependencies between project tasks. Route planners and recommendation systems rely heavily on graph algorithms.

Remember: There is no best data structure in general, only the best one for a particular pattern of use. Ask which operations will be most frequent: looking up, adding, removing or keeping things in order.

Choosing a structure

  • Need fast lookup by an identifier? Consider a hash table.
  • Need items in order of arrival? Use a queue.
  • Need to reverse the most recent actions? Use a stack.
  • Need sorted data with fast search? Consider a tree, or a sorted array if the data rarely changes.
  • Need to represent connections or networks? Use a graph.

In practice

You meet these ideas outside programming too. A spreadsheet lookup on a unique code behaves like a dictionary; a ticketing system that serves the oldest request first is a queue; a project plan with task dependencies is a graph. When a system becomes slow as data grows, an inappropriate data structure is a common cause. A developer who replaces repeated searches through a long list with a dictionary lookup can sometimes turn minutes of processing into seconds.

3.2 Searching and sorting

Searching for an item and putting items in order are among the most common tasks a computer performs. They are also the classic way of learning about algorithms, because several different methods exist and their performance differs dramatically as the amount of data grows.

Linear search

The simplest way to find an item is to look at each one in turn until you find it or reach the end. This is called linear search. It works on any list, sorted or not, and is perfectly adequate for small amounts of data. But its running time grows in direct proportion to the size of the list. Searching a million records may mean checking a million items.

Binary search

If the list is already sorted, a far faster method is available. Binary search works like looking up a word in a printed dictionary:

  1. Look at the middle item.
  2. If it is the item you want, stop.
  3. If the item you want comes earlier, repeat the search on the first half; if later, on the second half.
  4. Continue until the item is found or there is nothing left to search.

Each step halves the remaining data. A list of a million sorted items needs at most about 20 comparisons, because 2 multiplied by itself 20 times is just over a million. Doubling the list to two million items adds only one more step. This shows a central lesson of computer science: a better algorithm can matter far more than a faster computer.

Tip: Binary search only works on sorted data. If data is searched often but changes rarely, it is usually worth sorting it once, or keeping it sorted, so that every later search is fast.

Sorting algorithms

There are many ways to sort a list, and comparing them teaches a great deal about efficiency.

AlgorithmBasic ideaTypical performance on large lists
Bubble sortRepeatedly swap neighbouring items that are in the wrong orderSlow; mainly used for teaching
Insertion sortTake each item and insert it into the correct place among those already sortedSlow in general, but fast on small or nearly sorted lists
Merge sortSplit the list in half, sort each half, then merge the two sorted halvesFast and predictable
QuicksortPick a "pivot", put smaller items before it and larger after, then sort each sideUsually very fast, though slow in rare worst cases

Merge sort and quicksort use a powerful strategy called divide and conquer: break a problem into smaller versions of itself, solve those, and combine the results. Many divide-and-conquer algorithms are written using recursion, where a function calls itself on a smaller part of the problem until it reaches a case simple enough to solve directly, such as a list with one item.

Stability and practical sorting

A sorting algorithm is stable if items that compare as equal keep their original order. This matters when sorting by more than one field. For example, if a list of staff is already in alphabetical order and you then sort it by department using a stable sort, each department's staff remain alphabetical. Spreadsheet and database sorts generally behave in this helpful way, which is why sorting by a secondary field first and the primary field second often works.

In real projects, programmers rarely write their own sorting algorithms. Modern languages provide well-tested sorting functions, often combining several techniques, that are faster and more reliable than most hand-written versions. The value of studying sorting lies in understanding the trade-offs, not in reimplementing it.

Common mistakes

  • Applying binary search to data that is not sorted, which gives wrong answers without any error.
  • Sorting a large list repeatedly inside a loop rather than once beforehand.
  • Sorting numbers stored as text, which places "100" before "20".

In practice

When a report or system becomes slow as data grows, ask how it searches and sorts. Is it scanning every record each time something is looked up? Could the data be sorted or indexed once? The same thinking applies to manual work: a sorted, consistently labelled archive can be searched far more quickly than an unordered one, for exactly the same reason that binary search beats linear search.

3.3 Measuring efficiency: an introduction to Big O

Two programs can produce identical results yet differ enormously in how long they take or how much memory they need, especially as data grows. Computer scientists need a way to describe this difference that does not depend on the speed of a particular computer, the programming language used or the skill of the programmer. The standard tool is Big O notation.

The core idea

Big O describes how the work an algorithm does grows as the size of its input grows. The size is usually written as n, for example the number of records in a list. Rather than measuring seconds, we ask: if n doubles, what happens to the amount of work? Big O focuses on the dominant trend for large inputs and ignores small details and constant factors. It usually describes the worst case, though average cases are also discussed.

Common growth rates

  • O(1), constant time: the work stays the same however large the data. Looking up an item in an array by its position, or in a hash table by its key, is typically constant time.
  • O(log n), logarithmic time: the work grows very slowly, adding one step each time the data doubles. Binary search is the classic example.
  • O(n), linear time: the work grows in proportion to the data. Linear search and adding up every value in a list are linear.
  • O(n log n): slightly more than linear. Efficient sorting algorithms such as merge sort fall into this category.
  • O(n squared), quadratic time: the work grows with the square of the data. Doubling the data makes the work four times larger. Comparing every item with every other item, as bubble sort does, is quadratic.
  • O(2 to the power n), exponential time: the work doubles with each extra item. Such algorithms become impractical even for modest inputs.

Why growth rates matter

For small inputs, the differences hardly matter. A quadratic algorithm handling 100 items performs around 10,000 basic steps, which a modern computer completes in a fraction of a second. With a million items it performs around a million million steps, which could take hours. A linear algorithm on the same million items performs about a million steps. This is why software that works well in testing with a small sample can fail badly once it meets real volumes of data.

Remember: Big O tells you how an approach scales, not exactly how fast it is. For small data, a "slower" algorithm with simple steps may actually win.

Spotting complexity in code

You can often estimate complexity by looking at the structure of an algorithm:

  1. A single loop through all the data suggests linear time.
  2. A loop inside another loop, both over the same data, suggests quadratic time.
  3. Repeatedly halving the data suggests logarithmic time.
  4. A fixed number of steps regardless of data size suggests constant time.

Hidden costs can mislead. A single loop that calls a function which itself searches the whole list on every pass is really quadratic, even though only one loop is visible.

Time and space trade-offs

Big O also describes memory use, called space complexity. Often you can trade one for the other. Building a hash table of customers takes extra memory but turns many slow searches into fast lookups. Storing previously calculated results, a technique called caching or memoisation, uses memory to avoid repeating work. Good engineering means choosing the right balance for the situation.

Limits of computation

Some problems have no known efficient solution. Finding the shortest route that visits every one of many delivery addresses exactly once, often called the travelling salesperson problem, becomes extremely expensive to solve exactly as the number of stops grows. In practice, organisations use heuristics: methods that find good, though not guaranteed best, answers quickly. Computer science also shows that some problems cannot be solved by any algorithm at all, an important result associated with Alan Turing's work in the 1930s.

In practice

When evaluating a system or a proposed solution, ask how it will behave when data grows by ten or a hundred times. Ask developers whether any part compares every record with every other record. When processing large spreadsheets, prefer lookups on sorted or indexed data over repeated full scans. These questions require no mathematics but can prevent expensive performance problems later.

Case study: Speeding up a duplicate check at a membership organisation

Northfield Rowing Association, a fictional national sports body, ran a nightly script to find duplicate member records before sending renewal reminders. When membership was small the script took a few seconds. After several clubs joined and membership grew to around 200,000 records, the script began to run for many hours and sometimes had not finished by morning.

A contract developer reviewed the code. For each member, it searched the whole list for anyone with the same email address, comparing every record with every other record. This was a quadratic algorithm: multiplying the data by ten had multiplied the work by roughly a hundred.

The developer rewrote the check to make a single pass through the records, storing each email address in a hash table as it went. Before adding an address, the script looked it up; if it was already present, the record was flagged as a possible duplicate. The new approach was linear and completed in under a minute. The association also added normalisation, such as converting addresses to lower case, so that near-identical entries were caught.

Activity

Think of a task in your work that involves searching, matching or sorting information, either by hand or with software. Describe how it is currently done and estimate whether its effort grows linearly, quadratically or more slowly as the amount of information grows. Then suggest a data structure or method that could make it more efficient.

Compare with a model answer

A good answer describes a specific task, for example matching supplier invoices to purchase orders in a spreadsheet. It explains the current method: for each invoice, someone scrolls or searches through the full list of orders. With n invoices and a similar number of orders, this approaches quadratic effort, so doubling the volume roughly quadruples the work.

It then proposes an improvement grounded in the unit. Sorting both lists by order number allows a single pass through each, or a lookup table keyed on order number allows each invoice to be matched almost instantly, giving roughly linear effort overall. The best answers mention a trade-off, such as the need to clean and standardise order numbers first, and consider unusual cases such as invoices that cover several orders.

Key takeaways

  • Data structures organise information for particular uses; arrays, linked lists, stacks, queues, hash tables, trees and graphs each have strengths and weaknesses.
  • Binary search is dramatically faster than linear search but requires sorted data.
  • Efficient sorting algorithms such as merge sort use divide and conquer, and in practice built-in sorting functions should be preferred.
  • Big O notation describes how work grows with input size, helping predict whether a solution will scale.
  • Nested loops over the same data often signal quadratic growth, which can turn into serious performance problems as data grows.

Unit check

Create a free account to answer the check, save your progress and receive your free certificate.

Create a free account Log in
← Unit 2 Unit 4 →
WhatsApp