Algorithms and OOD (CSC 207 2014S) : EBoards

CSC207.01 2014S, Class 20: Reasoning About Loops with Loop Invariants


Overview

Preliminaries

Admin

Upcoming Work

Homework 5

Choose your own partners. You may also work alone. You will be tested on many of these topics, so "divide and conquer" is not a good approach.

Part one: Solve some recurrence relations.

Part two: Implement Dutch National Flag, using invariants.

Part three: Implement Skip lists of strings, using invariants.

Part four: Implement iterative logn exponentiation, using invariants

Writing correct iterative algorithms

The state of a program

Loop invariants

Writing Loop Invariants

Loop termination

An exercise: Binary search

/** 
 * Find the index of val in values.
 */
public static int binarySearch(int[] values, int val)
{
  int lb = 0;
  int ub = values.length;

  // Invariant A: for all i, 0 <= i < lb, values[i] < val
  // Invariant B: for all i, ub <= i < length, values[i] > val
  while ((ub - lb) > 0)
    {
      int mid = average(lb, ub);
      if (values[mid] < val)
        lb = mid+1;
      else if (values[mid] > val)
        ub = mid;
      else
        return mid;
    } // while
  // At this point
  // Invariant A: for all i, 0 <= i < lb, values[i] < val
  // Invariant B: for all i, ub <= i < length, values[i] > val
  // lb >= ub
  // The element is not there
  throw new NotFound();

} // binarySearch(int[], int)

Lab

Copyright (c) 2013-14 Samuel A. Rebelsky.

Creative Commons License

This work is licensed under a Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.