241-303 Discrete Maths: Invariant/2 1 Discrete Maths Objectives – –to show the use of induction for proving properties of code involving loops use induction.

Slides:



Advertisements
Similar presentations
SORTING Lecture 12B CS2110 – Spring InsertionSort 2 pre: b 0 b.length ? post: b 0 b.length sorted inv: or: b[0..i-1] is sorted b 0 i b.length sorted.
Advertisements

Bubble Sort Algorithm 1.Initialize the size of the list to be sorted to be the actual size of the list. 2.Loop through the list until no element needs.
MATH 224 – Discrete Mathematics
CS 1031 Recursion (With applications to Searching and Sorting) Definition of a Recursion Simple Examples of Recursion Conditions for Recursion to Work.
Discussion #33 Adjacency Matrices. Topics Adjacency matrix for a directed graph Reachability Algorithmic Complexity and Correctness –Big Oh –Proofs of.
 Sort: arrange values into an order  Alphabetical  Ascending numeric  Descending numeric  Does come before or after “%”?  Two algorithms considered.
Insertion sort, Merge sort COMP171 Fall Sorting I / Slide 2 Insertion sort 1) Initially p = 1 2) Let the first p elements be sorted. 3) Insert the.
Simple Sorting Algorithms
Lecture 12 Oct 13, 2008 Some simple recursive programs recursive problem solving, connection to induction Some examples involving recursion Announcements.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
Chapter 3: Sorting and Searching Algorithms 3.2 Simple Sort: O(n 2 )
Algorithm Efficiency and Sorting
Proving correctness. Proof based on loop invariants  an assertion which is satisfied before each iteration of a loop  At termination the loop invariant.
Lecture 4 Discrete Mathematics Harper Langston. Algorithms Algorithm is step-by-step method for performing some action Cost of statements execution –Simple.
Sorting Arrays. Selection Sort  One of the easiest ways to sort the elements of an array is by using the selection sort algorithm.  Assume that the.
DAST 2005 Tirgul 6 Heaps Induction. DAST 2005 Heaps A binary heap is a nearly complete binary tree stored in an array object In a max heap, the value.
Value Iteration 0: step 0. Insertion Sort Array index67 Iteration i. Repeatedly swap element i with.
Simple Sorting Algorithms. 2 Bubble sort Compare each element (except the last one) with its neighbor to the right If they are out of order, swap them.
Discrete Maths Objective to show the close connection between recursive definitions and recursive functions , Semester 2, Recursion.
Simple Sorting Algorithms. 2 Outline We are going to look at three simple sorting techniques: Bubble Sort, Selection Sort, and Insertion Sort We are going.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Algorithm Design and Analysis (ADA)
What it is? Why is it a legitimate proof method? How to use it?
MATH 224 – Discrete Mathematics
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Recursion.
Reading and Writing Mathematical Proofs
Discrete Maths Objective to introduce mathematical induction through examples , Semester 2, Mathematical Induction 1.
Reasoning with invariants Jordi Cortadella Department of Computer Science.
1 Inference Rules and Proofs (Z); Program Specification and Verification Inference Rules and Proofs (Z); Program Specification and Verification.
CSI 3125, Axiomatic Semantics, page 1 Axiomatic semantics The assignment statement Statement composition The "if-then-else" statement The "while" statement.
Discrete Maths Objective to describe the Big-Oh notation for estimating the running time of programs , Semester 2, Running Time of.
Discrete Mathematics Tutorial 11 Chin
Examples using Arrays. Summing Squares Problem: To compute the sum of the squares of N numbers N is given N values are also given These should be read.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
Computer Science School of Computing Clemson University Discrete Math and Reasoning about Software Correctness Joseph E. Hollingsworth
Discrete Maths: Induction/1 1 Discrete Maths Objective – –to introduce mathematical induction through examples , Semester
Application: Correctness of Algorithms Lecture 22 Section 4.5 Fri, Mar 3, 2006.
Reading and Writing Mathematical Proofs Spring 2015 Lecture 4: Beyond Basic Induction.
September 17, 2001 Algorithms and Data Structures Lecture II Simonas Šaltenis Nykredit Center for Database Research Aalborg University
Data Structure Introduction.
Chapter 5: Sequences, Mathematical Induction, and Recursion 5.5 Application: Correctness of Algorithms 1 [P]rogramming reliability – must be an activity.
MATH 224 – Discrete Mathematics
Application: Correctness of Algorithms Lecture 22 Section 4.5 Fri, Feb 18, 2005.
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.
September 9, Algorithms and Data Structures Lecture II Simonas Šaltenis Nykredit Center for Database Research Aalborg University
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Arrays An array is a data object that can hold multiple objects, all of the same type. We can think of an array as a storage box which has multiple compartments.
Chapter 6 Recursion. Solving simple problems Iteration can be replaced by a recursive function Recursion is the process of a function calling itself.
The Sorting Methods Lecture Notes 10. Sorts Many programs will execute more efficiently if the data they process is sorted before processing begins. –
2IS80 Fundamentals of Informatics Fall 2015 Lecture 6: Sorting and Searching.
1 2/21/2016 MATH 224 – Discrete Mathematics Sequences and Sums A sequence of the form ar 0, ar 1, ar 2, ar 3, ar 4, …, ar n, is called a geometric sequence.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
1 Computer Algorithms Tutorial 2 Mathematical Induction Some of these slides are courtesy of D. Plaisted et al, UNC and M. Nicolescu, UNR.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
September 18, Algorithms and Data Structures Lecture II Simonas Šaltenis Aalborg University
CORRECTNESS ISSUES AND LOOP INVARIANTS Lecture 8 CS2110 – Fall 2014.
Week 4 – Functions Coding Functions. Purpose of Coding Functions A function is written to perform a well-defined task; rather than having all logic in.
CORRECTNESS ISSUES AND LOOP INVARIANTS Lecture 8 CS2110 – Fall 2015.
ALGORITHMS PROVING ALGORITHMS (PROGRAMS) CORRECT WITH AND WITHOUT INDUCTION.
Recursive Definitions
MATH 224 – Discrete Mathematics
Reasoning with invariants
Copyright © Cengage Learning. All rights reserved.
Selection sort Given an array of length n,
Axiomatic semantics Points to discuss: The assignment statement
Discrete Maths 11. Recursion Objective
Mathematical Induction
Simple Sorting Algorithms
Simple Sorting Algorithms
11.4 Mathematical Induction
Presentation transcript:

Discrete Maths: Invariant/2 1 Discrete Maths Objectives – –to show the use of induction for proving properties of code involving loops use induction to prove that functions work – –introduce pre- and post- conditions, loop termination , Semester Loop Invariants

Discrete Maths: Invariant/2 2 Overview 1. What is a Loop Invariant? 2. Three simple examples – –they involve while loops 3. Selection Sort 4. Further Information

Discrete Maths: Invariant/ What is a Loop Invariant? A loop invariant is an inductive statement which says something which is always true about a program loop. Loop invariants are useful for: – –code specification – –debugging continued

Discrete Maths: Invariant/2 4 A loop invariant is typically written as an inductive statement S(n), where n is some changing element of the loop. For example: – –the loop counter/index – –a loop variable which changes on each iteration

Discrete Maths: Invariant/ Example 1 int square(int val) { int result = 0; int counter = 0; while (counter < val) { result += val; counter++; } return result; } Problem: does this function work?

Discrete Maths: Invariant/2 6 We assume that val is a positive integer – –the precondition for this function square() always returns val 2 – –the postcondition – –we will use the loop invariant to show that this is true Pre- and Post-conditions

Discrete Maths: Invariant/2 7 The Loop Invariant To make the proof clearer, let counter n and result n be the values of counter and result after passing round the loop n times. Loop invariant S(n): result n = val * counter n – –is this true in the loop for all n >= 0?

Discrete Maths: Invariant/2 8 Basis S(0) is when the loop has not yet been executed. – –result 0 = counter 0 = 0 So: result 0 = val * counter 0 – –which means that S(0) is true.

Discrete Maths: Invariant/2 9 Induction We assume that S(k) is true for some k >= 0, which means that: result k = val * counter k (1) After one more pass through the loop: result k+1 = result k + val(2) counter k+1 = counter k + 1(3) continued

Discrete Maths: Invariant/2 10 Substitute the rhs of (1) for the 1st operand of the rhs of (2): result k+1 = (val * counter k ) + val = val * (counter k + 1) = val * counter k+1 (by using (3)) – –this is S(k+1), which is therefore true. continued

Discrete Maths: Invariant/2 11 For the loop, we now know: – –S(0) is true – –S(k) --> S(k+1) is true That means S(n) is true for all n >= 0 – –for all n >= 0, the loop invariant is true: result n = val * counter n

Discrete Maths: Invariant/2 12 Termination The loop does actually terminate, since counter is increasing, and will reach val. At loop termination (and function return): counter n = val So in S(n): result n = val * val = val 2 So the postcondition is true. The function works!!

Discrete Maths: Invariant/ Example 2 int exp(int b, int m) // return b m { int res = 1; while (m > 0) { res = res * b; m = m - 1; } return res; } Problem: does this function work?

Discrete Maths: Invariant/2 14 We assume b and m are non-negative integers – –the preconditions for this function exp() always returns b m – –the postcondition – –we will use the loop invariant to show that this is true Pre- and Post-conditions

Discrete Maths: Invariant/2 15 The Loop Invariant To clarify the proof, let res n and m n be the values of res and m after passing round the loop n times. Loop invariant S(n): res n * b m n = b m – –is this true in the loop for all n >= 0? Inventing this is the hardest part.

Discrete Maths: Invariant/2 16 Basis S(0) is when the loop has not yet been executed. – –res 0 = 1; m 0 = m So: 1 * b m = b m – –which means that S(0) is true.

Discrete Maths: Invariant/2 17 Induction We assume that S(k) is true for some k >= 0, which means that: res k * b m k = b m (1) After one more pass through the loop: res k+1 = res k * b(2) m k+1 = m k - 1(3) continued

Discrete Maths: Invariant/2 18 Rearrange the equations: res k = res k+1 / b(2’) m k = m k+1 + 1(3’) Substitute the right hand sides of (2’) and (3’) into (1): ( res k+1 / b ) * b (m k ) = b m which is res k+1 * b (m k ) = b m which is res k+1 * b m k+1 = b m continued

Discrete Maths: Invariant/2 19 S(k+1) is: res k+1 * b m k+1 = b m (4) So we have shown S(k+1) is true by using S(k). continued

Discrete Maths: Invariant/2 20 For the loop, we now know: – –S(0) is true – –S(k) --> S(k+1) is true That means S(n) is true for all n >= 0 – –for all n >= 0, the loop invariant is true: res n * b m n = b m

Discrete Maths: Invariant/2 21 Termination The loop does actually terminate, since m is decreasing, and will reach 0. At loop termination (and function return): m n = 0 So in S(n): res n * b 0 = b m so res n = b m So the postcondition is true. The function works!!

Discrete Maths: Invariant/ Example 3 int factorial(int num) { int i = 2; int fact = 1; while (i <= num) { fact = fact * i; i++; } return fact; } Problem: does this function work?

Discrete Maths: Invariant/2 23 We assume num is a positive integer – –the precondition for this function factorial() always returns num! – –the postcondition – –we will use the loop invariant to show that this is true Pre- and Post-conditions

Discrete Maths: Invariant/2 24 The Loop Invariant To clarify the proof, let fact n and i n be the values of fact and i after passing round the loop n times. Loop invariant S(n): fact n = (i n - 1)! – –is this true in the loop for all n >= 0?

Discrete Maths: Invariant/2 25 Basis S(0) is when the loop has not yet been executed. – –i 0 = 2; fact 0 = 1 So:fact 0 = (i 0 - 1)! 1 = (2 - 1)! 1 = 1 which means that S(0) is true.

Discrete Maths: Invariant/2 26 Induction We assume that S(k) is true for some k >= 0, which means that: fact k = (i k -1)!(1) After one more pass through the loop: fact k+1 = fact k * i k (2) i k+1 = i k + 1(3) continued

Discrete Maths: Invariant/2 27 Substitute the rhs of (1) for the 1st operand of the rhs of (2): fact k+1 = (i k - 1)! * i k = (i k )! = (i k+1 - 1)! (by using (3)) – –this is S(k+1), which is therefore true. continued

Discrete Maths: Invariant/2 28 For the loop, we now know: – –S(0) is true – –S(k) --> S(k+1) is true That means S(n) is true for all n >= 0 – –for all n >= 0, the loop invariant is true: fact n = (i n - 1)!

Discrete Maths: Invariant/2 29 Termination The loop does actually terminate, since i is increasing, and will reach num+1. At loop termination (and function return): i n = num+1 So in S(n): – –fact n = (i n - 1)! = (num )!= num! So the postcondition is true. The function works!!

Discrete Maths: Invariant/ Selection Sort void selectionSort(int A[], int num) { int i, j, small, temp; for (i=0; i < num-1; i++) { small = i; for( j= i+1; j < num; j++) if (A[j] < A[small]) small = j; temp = A[small]; A[small] = A[i]; A[i] = temp; } } swap A[small] and A[i] put index of smallest value in A[i.. num-1] into small

Discrete Maths: Invariant/2 31 Execution Highlights A Start 1st iteration: A sorted A sorted Start 4th iteration: A sorted Start 2nd iteration: Start 3rd iteration: selectionSort(A, 4);

Discrete Maths: Invariant/2 32 We assume num is a positive integer, which contains the number of elements in the array – –the precondition for this function selectionSort() sorts the array into ascending order – –the postcondition – –we will use the loop invariant to show that this is true Pre- and Post-conditions

Discrete Maths: Invariant/ Consider the Inner Loop small = i; for( j= i+1; j < num; j++) if (A[j] < A[small]) small = j; Put index of smallest value in A[i.. num-1] into small

Discrete Maths: Invariant/2 34 We assume i is a positive integer, which is an index into the array – –the precondition for this part of the code This code finds the index of the smallest value in A[i..num-1] – –the postcondition – –we will use the loop invariant to show that this is true Pre- and Post-conditions

Discrete Maths: Invariant/2 35 The Inner Loop Invariant To clarify the proof, let small n and j n be the values of small and j after passing round the loop n times. Loop invariant S(n): small n is the index of the smallest of A[i.. j n -1] – –is this true in the loop for all n >= 0?

Discrete Maths: Invariant/2 36 Execution Highlights A Start 1st pass:small 0 j A small 0 j A small 2 j A small 3 j Start 2nd pass: Start 3rd pass: Start 4th pass: loop ends

Discrete Maths: Invariant/2 37 Basis S(0) is when the loop has not yet been executed. – –small 0 = i; j 0 = i+1 So: small 0 is the index of the smallest of A[i.. j 0 -1] which is A[i..(i+1-1)], or A[i..i], or A[i] That means that S(0) is true.

Discrete Maths: Invariant/2 38 Induction We assume that S(k) is true for some k >= 0, which means that: small k is the index of the smallest of A[i.. j k -1] The pass through the loop involves two possible branches because of the if. continued

Discrete Maths: Invariant/2 39 Case 1. If A[j k ] is not smaller than the smallest of A[i.. j k -1] – –then small k+1 = small k (no change) Case 2. If A[j k ] is smaller than the smallest of A[i.. j k -1] – –then small k+1 = j k continued

Discrete Maths: Invariant/2 40 At the end of the pass: – –small k+1 is the index of the smallest of A[i..j k ] – –j k+1 = j k + 1 S(k+1) is: – –small k+1 is the index of the smallest of A[i.. j k+1 -1] So S(k+1) is true. continued

Discrete Maths: Invariant/2 41 For the inner loop, we now know: – –S(0) is true – –S(k) --> S(k+1) is true That means S(n) is true for all n >= 0 – –for all n >= 0, the inner loop invariant is true: small n is the index of the smallest of A[i.. j n -1]

Discrete Maths: Invariant/2 42 Termination The loop does actually terminate, since j is increasing, and will reach num. At loop termination: j n = num So in S(n): – –small n is the index of the smallest of A[i.. j n -1], or A[i..num-1] So the postcondition is true. The inner loop is proved.

Discrete Maths: Invariant/ The Outer Loop void selectionSort(int A[], int num) { int i, j, small, temp; for (i=0; i < num-1; i++) { small = i; for( j= i+1; j < num; j++) if (A[j] < A[small]) small = j; temp = A[small]; A[small] = A[i]; A[i] = temp; } } proved

Discrete Maths: Invariant/2 44 The Outer Loop Invariant To clarify the proof, let i m be the value of i after passing round the loop m times. Informal loop invariant T(m): i m indicates that we have selected m of the smallest elements and sorted them at the beginning of the array.

Discrete Maths: Invariant/2 45 Graphically A 0 Sorted < mm-1 current sort position i num-1 e.g i m smaller values in array larger values in array

Discrete Maths: Invariant/2 46 More Formally Loop invariant T(m): – –a) A[0..i m -1] are in sorted order; – –b) All of A[i m..num-1] are >= all of A[0..i m -1]

Discrete Maths: Invariant/2 47 Basis T(0) is when the loop has not yet been executed. i 0 =0 – –a) Range is A[0..-1], which means no elements. – –b) Range is A[0..num-1] which means everything > A[0..-1] So T(0) is true.

Discrete Maths: Invariant/2 48 Induction We assume that T(k) is true for some k >= 0, which means that: – –a) A[0..i k -1] are in sorted order; – –b) All of A[i k..num-1] are >= all of A[0..i k -1] continued

Discrete Maths: Invariant/2 49 By the end of the inner loop, we know that A[small] is the smallest element in A[i k..num-1] – –the postcondition of the inner loop The next three lines swap A[small] and A[i k ] – –now A[i k ] contains the smallest element continued

Discrete Maths: Invariant/2 50 Graphically A 0 Sorted < k k-1 current sort position i k num ikik k small swapped smalle.g. continued

Discrete Maths: Invariant/2 51 By the end of the outer loop, we know: – –a) A[0..i k ] are in sorted order; – –b) All of A[i k +1..num-1] are >= all of A[0..i k ] – –i k+1 = i k +1 This shows that T(k+1) is true. continued

Discrete Maths: Invariant/2 52 For the outer loop, we now know: – –T(0) is true – –T(k) --> T(k+1) is true That means T(m) is true for all m >= 0 – –a) A[0..i m -1] are in sorted order; – –b) All of A[i m..num-1] are >= all of A[0..i m -1]

Discrete Maths: Invariant/2 53 Termination The outer loop does actually terminate, since i is increasing, and will reach num-1. At loop termination (and function return): i m = num-1 continued

Discrete Maths: Invariant/2 54 So in T(m): – –a) A[0..i m -1] are in sorted order – –so A[0..num-1-1] is sorted – –so A[0..num-2] is sorted – –all the array up to the last element is sorted continued

Discrete Maths: Invariant/2 55 – –b) All of A[i m..num-1] are >= all of A[0..i m -1] – –so, A[num-1..num-1] >= all A[0..num-1-1] – –so, A[num-1] >= all A[0..num-2] – –so the last element is bigger than all the other array elements So the function does sort the array into ascending order: the postcondition is true

Discrete Maths: Invariant/ Further Information Discrete Mathematics Structures in Computer Science B. Kolman & R. C. Busby Prentice-Hall, 1987, 2nd ed. Section 1.6