Skip to main content
Ctrl+K

Laptop Lab

Mathematics

  • Figures
  • Calculus
    • Pre Calculus
      • Euclidean Trigonometry
      • Conic Sections
    • The Calculus
      • Limits
      • Derivatives
      • Integration
        • Integration
        • Techniques of Integration
        • Double Integration
        • Triple Integration
        • The Bell Curve, Gaussian Integral, & Error Function
        • HW1
      • Indeterminate Forms
      • Sequences & Series
      • Elementary Complex Analysis
    • Vector Calculus
      • Vectors
      • Dot Product
      • Vector Projection
      • Cross Product
      • Vector Functions
      • Gradient
      • Vector Fields
      • Line Integrals of Vector Fields
      • Curves & Surfaces and their Parameterizations
      • Coordinate Systems
        • Polar Coordinates
        • Cylindrical Coordinates
        • Spherical Coordinates
        • Transformations
    • Matrix Calculus
    • Tensor Calculus
    • Variational Calculus
  • Functions
    • Absolute Value
    • Boxcar Function
    • Floor and Ceiling
    • Heaviside Function
    • Ramp Function
    • Continuous Uniform Function
  • Linear Algebra
    • Introduction to Linear Systems
    • Linear Combinations
    • Homogeneity of Linear Systems
    • Linear Independence
    • Linear Transformations
    • More on Linear Transformations
    • Invertible Matrices
    • Vectors
    • Matrices
    • Some examples of the use of KaTeX
  • Algebra
    • Book: A Transition to Advanced Mathematics
  • Number Theory
    • Arithmetic
    • Fractions
    • Mathematical Induction
    • Binomial
    • Fibonacci
    • Division
    • Residues
    • Arithmetic Functions
    • Polynomials
    • Primitive Roots
    • Quadratic Residues
    • Exercises
    • Implementations
    • Book: Numbers, Groups, and Codes
      • Introduction
      • GCD & Euclid’s Algorithm
      • Congruence
      • Linear Congruences
      • 1.1
      • 1.2
      • 1.3
      • 1.4
      • 1.5
  • Logic
    • Introduction
  • Discrete Mathematics
    • Elementary Set Theory
    • Order Theory
    • Relations
    • Combinatorics
    • Formal Languages and Machines
  • Error-Correcting Codes
    • FCCT
      • Introduction to error-correcting codes
      • The main coding theory problem
      • Exercises
    • ECFF
      • Introduction & Block Codes, Weight, and Distance
      • Exercises
    • Codes
      • Repetition Codes
      • Parity Check Codes
      • Triple Check Code
      • Intro to binary codes C1, C2, C3
      • (32,64,16) Reed-Muller Code
  • Linear Programming
    • Some Definitions & Graphing
    • Convexity
    • Cones & Dual Cones
    • Row Tableaux
    • Dual LP & Sensitivity Analysis
    • Example
    • [13.2] Production Problem
    • Midterm II
  • Numerical Methods & Scientific Computing
  • More Math
    • Summations
    • Computer Algebra Systems

Computer Science & Engineering

  • Systems
    • C
    • Shell
      • Bash
    • Network Programming
    • OS
      • macOS
      • macOS Utilities
      • Windows
      • Windows Utilities
    • Distributed
      • Blockchain
      • Bitcoin
      • Ethereum
    • Hardware
    • Embedded
    • Filesystem
  • DS&A
    • Algorithms
    • Data Structures
      • Linked List
      • Stack
      • Queue
      • Priority Queue
    • Arithmetic
      • Array Sum
      • Integer Multiplication
    • Deduplication
    • Merge
      • Sorted Array Merge
      • \(k\)-Way Merge
    • Select
      • Naive Selection: \(k\)-th smallest element
      • Quickselect
    • Sort
      • Insertion Sort
      • Bubble Sort
      • Merge Sort
      • Selection Sort
      • Quick Sort
    • Search
      • Linear Search
      • Binary Search
    • Trees & Graphs
      • Trees
      • Graphs
    • Optimization
      • Linear Programming
      • Dynamic Programming
        • Lucas Numbers
        • Bellman-Ford
        • 0-1 Knapsack
    • PSU CMPSC 465
      • Assignment 1
      • Assignment 2
      • Assignment 3
      • Assignment 4
      • Assignment 5
      • Midterm
      • Assignment 6
      • Assignment 7
      • Assignment 8
      • Final
  • Programming
    • Editors
      • Vim
      • VSCode
    • Assembly
    • https://github.com/heracliteanflux/systems/tree/main/clang
    • Python
      • Packages
      • Data Science from Scratch 2e
    • R
      • Data Computing 2
      • R for Data Science 1
      • Silge & Robinson’s Text Mining with R
      • Forecasting: Principles and Practice 3
      • A01 - Tidy Data
      • A02 - Graphical Exploration
      • A04 - Data Wrangling
      • A05 - Project: Popular Names
      • A06 - Project: Bird Species
      • A07 - Project: Bicycle Sharing
      • A08 - Project: Scraping Nuclear Reactors
      • A09 - Project: Street or Road?
      • A10 - Base R
    • Go
    • D
    • Ruby
    • Notebook
    • Web
    • VR
    • Software Development
    • Documentation
    • Troubleshooting
  • Security
    • AI Sec
    • Cloud
    • Cryptography
    • CTF
      • OverTheWire
      • AOC2023
    • Defensive Sec
    • DevOps
    • Digital Forensics
    • DNS
    • GitOps
      • Git
      • GitHub
    • Hardware Sec
    • IoT
    • Malware
    • Mobile
    • Networking
      • Ethernet
      • Internet Protocol
    • OffSec
    • Passwords
    • Privacy
    • SSH
    • VMs
    • WebSec
  • Data
    • Relational
      • Postgres
      • MySQL
      • SQLite
      • Derby
    • NoSQL
    • Big Data
    • Files
    • Date Times
    • Unicode
    • Graph Data
  • Information
  • Computation
  • Artificial Intelligence
    • Robotics
    • Prompt Engineering
  • Graphics
  • Retro Gaming

Other Stuff

  • Languages & Linguistics
    • Linguistics
      • Phonetics
        • Articulatory Phonetics
        • The Acoustic Theory of Speech Production
        • Speech Processing
        • Auditory Phonetics
        • Speech Perception
        • Analysis of Speech Sounds
        • Acoustic properties of Anii vowels
        • Acoustics and audition
        • Sociophonetic properties of vowels and fricatives
        • Analysis of a stop continuum
        • Acoustic and auditory properties of speech sounds
      • Phonology
      • Morphology & Syntax
      • Semantics
      • Historical Linguistics
    • Languages
      • Constructed
      • Latin
    • Literature
      • Poetry
      • Rhetoric
      • Science Fiction
      • Tolkien
  • Philosophy
    • Ancient Philosophy
      • Ancient Near East
      • Archaic Greece
      • The Milesians
      • Anaxagoras
      • Heraclitus
      • Parmenides
      • Empedocles
      • Socrates
      • Plato
      • Aristotle
      • Atomism
      • The Megarians and Dialectic
      • Philosophical Greek
    • Medieval Philosophy
    • Early Modern Philosophy
      • Galileo
        • The Assayer (1623)
      • Hobbes
      • Descartes
        • Meditations on First Philosophy (1641)
        • Meditation I: Concerning Those Things That Can Be Called into Doubt
        • Meditation II: Concerning the Nature of the Human Mind: That It Is Better Known Than the Body
        • Meditation III: Concerning God, That He Exists
        • Meditation IV: Concerning the True and the False
        • Meditation V: Concerning the Essence of Material Things, and Again Concerning God, That He Exists
        • Meditation VI: Concerning the Existence of Material Things, and the Real Distinction between Mind and Body
        • Elisabeth’s Objection
      • Spinoza
      • Leibniz
      • Newton
      • Locke
      • Hume
      • Berkeley
      • Kant
    • Metaphysics & Ontology
    • Epistemology
    • Ethics
    • Aesthetics
    • Existentialism
    • Philosophy of Law
    • Political Philosophy and its history
    • Philosophy of History and the History of Ideas
    • Friendship and Love
    • American Philosophy
    • Chinese Philosophy
    • French Philosophy
    • Japanese Philosophy
    • Spanish Philosophy
    • History and Philosophy of Science
    • History & Philosophy of Physics & Cosmology
    • History and Philosophy of Chemistry
    • Philosophy of Biology
    • History & Philosophy of Language & Linguistics
    • Philosophy of Math
    • Philosophy of Mind & Consciousness
    • Music
  • Science
    • Astronomy & Astrophysics
      • Telescopes
    • Chemistry
    • Electrical Engineering & Electronics
      • Electromagnetism
      • Electronics
      • Electrical
    • Health & Medicine
  • Home Lab & DIY
    • 3D Print
    • Audio
    • Auto
    • Building
    • EDC
    • Game
    • IAQ
    • Metal
    • Network

Binary Search

Contents

  • Contents
  • Improving upon linear search
  • Iterative/Incremental Binary Search
    • Complexity
      • Time
        • Worst Case
    • Correctness
    • Implementations
      • C
      • Python
  • Resources

Binary Search#


Contents#

Contents

  • Binary Search

    • Contents

    • Improving upon linear search

    • Iterative/Incremental Binary Search

      • Complexity

        • Time

          • Worst Case

      • Correctness

      • Implementations

        • C

        • Python

    • Resources


Improving upon linear search#

If the subarray being searched in linear search is already sorted, the searching algorithm can check the midpoint of the subarray against \(v\) and eliminate half the subarray from further consideration. Binary search repeats the procedure, halving the size of the remaining portion of the subarray each time.

Properly speaking, binary search cannot be implemented with a divide-and-conquer approach. This is because when a problem is divided into two subproblems, binary search does not need to solve both subproblems, just one.


Iterative/Incremental Binary Search#

 INPUT    an array A[1:n] of n sorted values in ascending order and a value x in A
OUTPUT    an index i such that x = A[i]

BINARY_SEARCH(A, n, x)
1    l = 0
2    r = n - 1
3    while l < r
4        m = (l + r) / 2   // m is the average of l and r rounded down
5        if x <= A[m]
6            r = m
7        else
8            l = m + 1
9    return l

Complexity#

Time#

Worst Case#

\(T(n) = T(n/2) + \Theta(1) = \Theta(\lg n)\)

Correctness#

\(\textbf{Invariant}\)

The array is sorted in ascending order.

\(0 \le l \le r \le n - 1\)

\(x \in A[l:r]\)

\(\textbf{Initialization}\)

That the array is sorted in ascending order is in the precondition of the program.

Since \(n\) is at least \(1\) by the precondition that \(x \in A\) and since \(l\) and \(r\) are initialized to \(0\) and \(n - 1\), respectively, the inequality is satisfied:

\(0 \le (0 = l) \le (r = n - 1) \le n - 1 \iff 1 \le n\)

\(x \in A[l:r]\) because \(A[l:r]\) is the whole array and \(x \in A\) is a precondition of the program.

\(\textbf{Maintenance}\)

Since the program does not alter the array, the array remains sorted in ascending order.

Let primes denote values after iteration. It must be shown that if \(0 \le l \le r \le n - 1\) and \(x \in A[l:r]\) (i.e., the invariant is true before iteration) then \(0 \le l' \le r' \le n - 1\) and \(x \in A[l':r']\) (i.e., the invariant is true after iteration).

Since \(m\) is the average of \(l\) and \(r\) rounded down, it is known that \(l \le m \le r\). But because the loop condition \(l \lt r\) is true and the value of \(m\) is rounded down, it is known that \(l \le m \lt r\).

\(\text{Case}\,\, x \le A[m]\)

In this case \(l' = l\) and \(r' = m\) and so \(0 \le l \le m \lt r \le n - 1 \implies 0 \le l' \le r' \le n - 1\).

Since \(x \in A[l:r]\) and \(x \le A[r']\) it is the case that \(x \in A[l':r']\)

\(\text{Case}\,\, x \gt A[m]\)

In this case \(l' = m + 1\) and \(r' = r\).

\(m \lt r \implies l' = m + 1 \le r = r' \implies 0 \le l' \le r' \le n - 1\)

Since \(x \in A[l:r]\) and \(x \ge A[l']\) it is the case that \(x \in A[l':r']\). Another way to look at this is that \(x \not\in A[l:m]\) but according to the invariant \(x \in A[l:r]\) so it must be the case that \(x \in A[m + 1:r] = A[l':r']\)

\(\textbf{Postcondition}\)

For the program to be correct it must be shown that \(A[l] = x\). If the loop condition is false it is the case that \(l \not\lt r \iff l \ge r\). The loop invariant guarantees that \(l \le r\). So it must be the case that \(l = r\).

The loop invariant also guarantees that \(x \in A[l:r]\), which has now been reduced to a single element; namely, \(x\).

\(\textbf{Termination}\)

The value \(r - l\) is guaranteed by the invariant to be nonnegative, we can choose \(\text{DF}_0 = 0\)

Case \(x \in A[l:m]\): \(m \lt r \iff (m - l = r' - l') \lt r - l\)

Case \(x \in A[m + 1:r]\): \(l \lt m + 1 \iff l - r \lt (m + 1 = l') - (r = r') \iff r' - l' \lt r - l\)

The quantity \(r - l\) gets strictly smaller on every iteration as long as \(l \lt r\) and so the loop eventually terminates.

Implementations#

C#

// binary_search.c

#include <stdio.h>

void print_array (int A[], int n) {
  for (int i = 0; i < n; i++) {
    printf("%d ", A[i]);
  }
  printf("\n");
}

int binary_search (int A[], int n, int x) {
  int l = 0;
  int r = n - 1;

  while (l < r) {
    int m = (l + r) / 2;
    if (x <= A[m])
      r = m;
    else
      l = m + 1;
  }

  return l;
}

int main () {
  int A[] = {1, 2, 3, 4, 5};
  int n   = sizeof(A) / sizeof(A[0]);
  int x   = 4;
  int result = binary_search(A, n, x);
  
  print_array(A, n);
  printf("Value %d at index %d\n", x, result);

  return 0;
}

Python#


Resources#

  • https://www.geeksforgeeks.org/binary-search/

  • https://www.khanacademy.org/computing/computer-science/algorithms/binary-search/a/binary-search

  • https://www.cs.cornell.edu/courses/cs2112/2020fa/lectures/lecture.html?id=loopinv

  • [ y ] 02-13-2023 Coding with John. “Binary Search in Java - Full Simple Coding Tutorial”.

  • [ y ] 12-01-2023 Computerphile. “Bug in Binary Search - Computerphile”.

  • [ y ] 11-01-2023 Computerphile. “Binary Search Algorithm - Computerphile”.


previous

Linear Search

next

Trees & Graphs

Contents
  • Contents
  • Improving upon linear search
  • Iterative/Incremental Binary Search
    • Complexity
      • Time
        • Worst Case
    • Correctness
    • Implementations
      • C
      • Python
  • Resources

By DF