Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Database › Indexes and execution plans

Binary search and B-trees

If the data is sorted, you can discard half at a time

Why it exists — If values are in no particular order, you have to compare them one by one from the start even to find a single one, and if the value is not there, you have to look at all of them to the end. Binary search, at the price of keeping the values sorted, removes half of the candidates with each comparison, and a B-tree splits each node into many branches to cut the number of reads from disk to a few.

Where it's used today — In Java, binary search is used when you search sorted arrays and lists with Arrays.binarySearch and Collections.binarySearch. The default indexes of MySQL (InnoDB) and PostgreSQL belong to the B-tree family, so conditions such as WHERE id = 5 or a range condition are handled without reading the whole table. If you do not need order and only search by an exact key, a hash-based method such as HashMap is used instead.

You look for one value among 27 values. You can check them one by one from the start. If they are sorted, you can look at the middle and discard half. Or you can use a B-tree, which splits the search into many branches at once.

Checked against real execution · The search on the screen is the result of actually running the algorithms

Concepts in this lab

Binary search
This search method works on sorted data: it compares the target with the middle value and cuts the search range in half each time. Its time complexity is O(log n). It can be used only when the data is sorted. A B-tree index in a database uses the same principle of narrowing the range over sorted data.
Time complexity (big-O notation)
Why it exists — If you measure running time in seconds, the value differs by computer and by input, so it is hard to say which of two approaches is better. Big-O notation drops constants and small terms and keeps only the shape of the growth as the input gets larger, so it lets you compare approaches regardless of the environment.
Where it's used today — It is used when choosing a data structure (contains is O(n) for ArrayList and O(1) on average for HashSet), when judging whether a double loop can withstand growing data, and when estimating whether a solution will finish in time in a coding test.
This notation shows how fast the number of operations of an algorithm grows as the input size n grows. O(1) means constant regardless of size, O(log n) means only one more step when the size doubles, O(n) means proportional to the size, and O(n²) means proportional to the square of the size. It is the basis for judging which approach holds up as the amount of data grows.
B-tree index
Why it exists — A binary tree on disk has one key per node, so its height grows when there are many rows, and it is slow because every node read is a disk read. A B-tree puts many keys in one disk page, so it finds a value with a few page reads.
Where it's used today — In MySQL InnoDB and PostgreSQL, a B-tree index is created when you do not specify the kind with CREATE INDEX. For lookups that only look for the same value, you can also choose a hash index in PostgreSQL.
The index structure that most relational databases use by default. It is a balanced tree that keeps values sorted, and each node holds many keys, so the height of the tree is low. You can find a value by going down only a few levels from the root. Because the values are sorted, it is used not only for equality lookups but also for range lookups and sorting.
Full table scan
A way of finding the rows that match a condition by reading every row of the table from beginning to end. It is chosen when no index can be used for the condition, or when an index exists but the optimizer judges that reading everything is better because too many rows match the condition. When it is used to find a few rows in a large table, it causes performance problems.
Index
A data structure that keeps the values of specific columns separately, in sorted form, so that the wanted rows of a table can be found quickly. Without one, the whole table must be read to find the rows that match a condition. Reads get faster, but it must also be updated every time data is inserted, updated, or deleted, so it costs write performance and storage space.

Try these

Running with the default settings

  1. The 27 values are piled up unsorted (on the screen they are shown in order of size to make them easier to read). There is nothing to tell where the value is, so you check the values one by one from the start.
  2. Check #1: 10 → No. Move to the next slot.
  3. Check #2: 20 → No. Move to the next slot.
  4. Check #6: 60 → No. Move to the next slot.
  5. Check #12: 120 → No. Move to the next slot.
  6. Check #18: 180 → No. Move to the next slot.
  7. Check #23: 230 → Found.

Result of this run

Code

// Only the method body is shown (the method declaration and its parameters rows and target are omitted)
// Unsorted array: check one by one from the start
for (int i = 0; i < rows.length; i++) {
    if (rows[i] == target) return i;
}
return -1;                              // you know it is missing only after checking to the end

-- In a database, this is the same as searching by a column that has no index (full table scan)
SELECT * FROM orders WHERE amount = 230;

Assumptions of this model

The search steps and counts for 27 rows are the result of this page actually running the algorithms. The counts for large numbers of rows are the maximum number of steps, calculated from "how many branches the search splits into at a time". The B-tree on the screen has the shape in which the values are only in the leaf nodes (a B+tree), and the index of MySQL InnoDB has this structure. How many values fit in one node of a real index depends on the size of the key, and 500 is just an example value. The root and internal nodes are usually already in memory, so the number of real disk reads is smaller.

Previous lab: Views, stored procedures, and triggers · Next lab: Indexes and full table scans

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these