Loop Invariants and Binary Search Chapter 4.4, 5.1.

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

ISBN Chapter 3 Describing Syntax and Semantics.
Object Oriented Design An object combines data and operations on that data (object is an instance of class) data: class variables operations: methods Three.
1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Software Engineering and Design Principles Chapter 1.
Search and Recursion CS221 – 2/23/09. List Search Algorithms Linear Search: Simple search through unsorted data. Time complexity = O(n) Binary Search:
Search and Recursion pt. 2 CS221 – 2/25/09. How to Implement Binary Search Take a sorted data-set to search and a key to search for Start at the mid-point.
Recursion. Binary search example postponed to end of lecture.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 18 Program Correctness To treat programming.
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (3) Recurrence Relation 11/11 ~ 11/14/2008 Yang Song.
Algorithm Efficiency and Sorting
Describing Syntax and Semantics
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Prof. Bodik CS 164 Lecture 16, Fall Global Optimization Lecture 16.
 2006 Pearson Education, Inc. All rights reserved Searching and Sorting.
COSC 3101NJ. Elder Announcements Midterm Exam: Fri Feb 27 CSE C Two Blocks: –16:00-17:30 –17:30-19:00 The exam will be 1.5 hours in length. You can attend.
1 “Not all recursive solutions are better than iterative solutions…” “… recursion, however, can provide elegantly simple solutions to problems of great.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
Chapter 3 (Part 3): Mathematical Reasoning, Induction & Recursion  Recursive Algorithms (3.5)  Program Correctness (3.6)
© by Kenneth H. Rosen, Discrete Mathematics & its Applications, Sixth Edition, Mc Graw-Hill, 2007 Chapter 4 (Part 3): Mathematical Reasoning, Induction.
Analysis of Algorithms Algorithm Input Output Last Update: Aug 21, 2014 EECS2011: Analysis of Algorithms1.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
1 Lecture 16: Lists and vectors Binary search, Sorting.
SEARCHING UNIT II. Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances.
 2005 Pearson Education, Inc. All rights reserved Searching and Sorting.
 Pearson Education, Inc. All rights reserved Searching and Sorting.
Searching. Linear (Sequential) Search Search an array or list by checking items one at a time. Linear search is usually very simple to implement, and.
Lecture 3.4: Recursive Algorithms CS 250, Discrete Structures, Fall 2011 Nitesh Saxena *Adopted from previous lectures by Zeph Grunschlag.
Chapter 13 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Recursive Functions for Tasks(13.1) Recursive Functions.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 14 Recursion.
Merge sort, Insertion sort. Sorting I / Slide 2 Sorting * Selection sort (iterative, recursive?) * Bubble sort.
CSC 211 Data Structures Lecture 13
CS Data Structures I Chapter 2 Principles of Programming & Software Engineering.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Searching UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative Commons.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Chapter 6 Recursion. Solving simple problems Iteration can be replaced by a recursive function Recursion is the process of a function calling itself.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
Data Structures - CSCI 102 Selection Sort Keep the list separated into sorted and unsorted sections Start by finding the minimum & put it at the front.
8.1 8 Algorithms Foundations of Computer Science  Cengage Learning.
2IS80 Fundamentals of Informatics Fall 2015 Lecture 6: Sorting and Searching.
1 Ch. 2: Getting Started. 2 About this lecture Study a few simple algorithms for sorting – Insertion Sort – Selection Sort (Exercise) – Merge Sort Show.
CSC317 1 So far so good, but can we do better? Yes, cheaper by halves... orkbook/cheaperbyhalf.html.
Lecture 2 What is a computational problem? What is an instance of a problem? What is an algorithm? How to guarantee that an algorithm is correct? What.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Recursion.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
BINARY SEARCH CS16: Introduction to Data Structures & Algorithms Thursday February 12,
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
CORRECTNESS ISSUES AND LOOP INVARIANTS Lecture 8 CS2110 – Fall 2014.
Central Algorithmic Techniques Iterative Algorithms.
16 Searching and Sorting.
Recursion Version 1.0.
Recursion Topic 5.
Chapter 3 of Programming Languages by Ravi Sethi
Recursion: The Mirrors
Chapter 14 Recursion. Chapter 14 Recursion Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively.
CS 3343: Analysis of Algorithms
Copyright © Cengage Learning. All rights reserved.
Programming Languages 2nd edition Tucker and Noonan
Search,Sort,Recursion.
CSE 373 Data Structures and Algorithms
Basics of Recursion Programming with Recursion
Search,Sort,Recursion.
Binary Search and Loop invariants
Programming Languages 2nd edition Tucker and Noonan
Presentation transcript:

Loop Invariants and Binary Search Chapter 4.4, 5.1

Outline  Iterative Algorithms, Assertions and Proofs of Correctness  Binary Search: A Case Study

Outline  Iterative Algorithms, Assertions and Proofs of Correctness  Binary Search: A Case Study

Assertions  An assertion is a statement about the state of the data at a specified point in your algorithm.  An assertion is not a task for the algorithm to perform.  You may think of it as a comment that is added for the benefit of the reader.

Loop Invariants  Binary search can be implemented as an iterative algorithm (it could also be done recursively).  Loop Invariant: An assertion about the current state useful for designing, analyzing and proving the correctness of iterative algorithms.

Other Examples of Assertions  Preconditions: Any assumptions that must be true about the input instance.  Postconditions: The statement of what must be true when the algorithm/program returns.  Exit condition: The statement of what must be true to exit a loop.

Iterative Algorithms Take one step at a time towards the final destination loop (done) take step end loop

From the Pre-Conditions on the input instance we must establish the loop invariant. Establishing Loop Invariant

Maintain Loop Invariant  Suppose that  We start in a safe location (pre-condition)  If we are in a safe location, we always step to another safe location (loop invariant)  Can we be assured that the computation will always be in a safe location?  By what principle?

Maintain Loop Invariant By Induction the computation will always be in a safe location.

Ending The Algorithm  Define Exit Condition  Termination: With sufficient progress, the exit condition will be met.  When we exit, we know  exit condition is true  loop invariant is true from these we must establish the post conditions. Exit 0 kmExit

Definition of Correctness &  If the input meets the preconditions, then the output must meet the postconditions. If the input does not meet the preconditions, then nothing is required.

Outline  Iterative Algorithms, Assertions and Proofs of Correctness  Binary Search: A Case Study

Define Problem: Binary Search  PreConditions  Key 25  Sorted List  PostConditions  Find key in list (if there)

Define Loop Invariant  Maintain a sublist.  If the key is contained in the original list, then the key is contained in the sublist. key

Define Step  Cut sublist in half.  Determine which half the key would be in.  Keep that half. key If key ≤ mid, then key is in left half. If key > mid, then key is in right half. mid

Define Step  It is faster not to check if the middle element is the key.  Simply continue. key If key ≤ mid, then key is in left half. If key > mid, then key is in right half.

Make Progress  The size of the list becomes smaller km75 km

Exit Condition  If the key is contained in the original list, then the key is contained in the sublist.  Sublist contains one element. Exit km If element = key, return associated entry. Otherwise return false. key 25

Running Time The sublist is of size n, n / 2, n / 4, n / 8,…,1 Each step O(1) time. Total = O(log n) key If key ≤ mid, then key is in left half. If key > mid, then key is in right half.

Running Time  Binary search can interact poorly with the memory hierarchy (i.e. caching), because of its random-access nature.caching  It is common to abandon binary searching for linear searching as soon as the size of the remaining span falls below a small value such as 8 or 16 or even more in recent computers.

Simple, right?  Although the concept is simple, binary search is notoriously easy to get wrong.  Why is this?

Boundary Conditions  The basic idea behind binary search is easy to grasp.  It is then easy to write pseudocode that works for a ‘typical’ case.  Unfortunately, it is equally easy to write pseudocode that fails on the boundary conditions.

Boundary Conditions or What condition will break the loop invariant?

Boundary Conditions key mid Bug!!

Boundary Conditions OK Not OK!!

key Boundary Conditions or Shouldn’t matter, right?

674 Boundary Conditions key If key ≤ mid, then key is in left half. If key > mid, then key is in right half. mid

Boundary Conditions key If key ≤ mid, then key is in left half. If key > mid, then key is in right half. mid

Boundary Conditions key If key ≤ mid, then key is in left half. If key > mid, then key is in right half. Another bug! No progress toward goal: Loops Forever! mid

Boundary Conditions OK Not OK!!

Getting it Right  How many possible algorithms?  How many correct algorithms?  Probability of guessing correctly?

Alternative Algorithm: Less Efficient but More Clear

 A volunteer, please. Card Trick

Pick a Card Done Thanks to J. Edmonds for this example.

Loop Invariant: The selected card is one of these.

Which column? left

Loop Invariant: The selected card is one of these.

Selected column is placed in the middle

I will rearrange the cards

Relax Loop Invariant: I will remember the same about each column.

Which column? right

Loop Invariant: The selected card is one of these.

Selected column is placed in the middle

I will rearrange the cards

Which column? left

Loop Invariant: The selected card is one of these.

Selected column is placed in the middle

Here is your card. Wow!

Ternary Search  Loop Invariant: selected card in central subset of cards  How many iterations are required to guarantee success?

Learning Outcomes  From this lecture, you should be able to:  Use the loop invariant method to think about iterative algorithms.  Prove that the loop invariant is established.  Prove that the loop invariant is maintained in the ‘typical’ case.  Prove that the loop invariant is maintained at all boundary conditions.  Prove that progress is made in the ‘typical’ case  Prove that progress is guaranteed even near termination, so that the exit condition is always reached.  Prove that the loop invariant, when combined with the exit condition, produces the post-condition.  Trade off efficiency for clear, correct code.