Computer Algorithms II Lecture Notes

9 October 2007 • Algorithm Correctness


Outline

Binary Search

Algorithm Correctness

Algorithm Specification

Binary Search Example

Correctness

Binary Search Example

Correctness Conditions

Key Idea

Idea Check

Program Sketch

Reducing the Range.

Reducing the Range..

Reducing the Range...

Reducing the Range....

Binary Search

Invariants

Iterations

Termination Arguments

Binary Search Example

Binary Search Analysis

Example 1

find(start, end, x, size)
  m = size/2
  if a[m] < x
    return find(start, m - 1, x, m)
  if a[m] > x
    return find(midpoint + 1, end, x, m)
  if a[m] = x
    return m
  if size = 1
    return -1

Analysis

find(start, end, x, size)
  m = size/2
    // What's the interval?
  if a[m] < x
    return find(start, m - 1, x, m)
      // The correct half-interval?
  if a[m] > x
    return find(m + 1, end, x, m)
      // The correct half-interval?
  if a[m] = x
    return m
  // How do you get here?
  if size = 1
    return -1

Example 2

find(a, x)
  first = 0
  last = a.size()
  i = last/2
  while (a[i] ≠ x) or 
        (last ≠ i and first ≠ i)
    if a[i] > x
      last = i
    else if a[i] < x
      first = i
    i = first + (last - first)/2
  if a[i] = x
    return x
  return -1

Analysis

while (a[i] ≠ x) or 
      (last ≠ i and first ≠ i)
  // Is a[i] defined?
  if a[i] > x
    last = i
  else if a[i] < x
    first = i
  i = first + (last - first)/2
  // Is the interval smaller?
if a[i] = x
  return x
return -1

Example 3

find(a, first, last, key)
  m = (first + last)/2
  if m > last
    return -1
  if a[m] = key
    return m
  if a[m] > key
    return find(a, m + 1, last, key)
  return find(a, first, m - 1, key)

Analysis

find(a, first, last, key)
  m = (first + last)/2
  if m > last
    return -1
  if a[m] = key
    return m
  if a[m] > key
    return find(a, m + 1, last, key)
      // The correct half interval?
  return find(a, first, m - 1, key)
    // The correct half interval?

Summary


This page last modified on 18 October 2007.

This work's CC license.