Lesson contents

Binary search

In a sorted sequence you can rule out half of the remaining positions by comparing the middle item with your target.

Simple example

Find 8. The middle value 6 is too small. Search the upper part and print position 4, counting from one.

Start2 4 6 8 10
Result4
main.go
package main

import "fmt"

func main() {
    values := []int{2, 4, 6, 8, 10}
    low := 0
    high := 4
    for low <= high {
        middle := low + ((high - low) / 2)
        if values[middle] == 8 {
            fmt.Println(middle + 1)
            break
        }
        if values[middle] < 8 {
            low = middle + 1
        } else {
            high = middle - 1
        }
    }
}
Output
4
Advertisements

Everyday examples

Open a numbered catalogue

You want page 84 in a catalogue. You open at 60. Which pages can you skip?

Start1…60…100
Result61…100

All pages through 60 come before 84. Look halfway through the remaining pages.

Check a reserved seat

Reserved seat numbers are 3, 7 and 11. Is seat 8 reserved?

Start3 7 11
Result∅

Seven is too small and eleven is too large. The remaining search interval is empty.

Find a date in a diary

A diary is ordered by date. Entries are on days 2, 5 and 9. Which single check finds day 5?

Start2 5 9
Result5

The middle date already matches. Stop immediately.

Cost and limits

Binary search uses O(log n) comparisons. The sequence must be sorted by the same rule used in the search.