Professional Documents
Culture Documents
Computer Programming II (TA C252, Lect 6)
Computer Programming II (TA C252, Lect 6)
Computer Programming II (TA C252, Lect 6)
Linear search
Unordered List
Ordered List
Binary search
Correctness issues
current=1;
while (current <=N) do
if (A[current] = = x) return current;
if(A[current]>x) return -1; // if sequence is ordered
current++;
endwhile;
return -1;
low = 1; high = N;
while (low < =high) do
mid = (low + high) /2;
if (A[mid] = = x) return mid;
else if (A[mid] < x) low = mid +1;
else high = mid – 1;
endwhile;
return -1;
10 15 18 21 25 33 41 53 55
33 41 53 55
10 15 18 21 25 33 41 53 55
10 15 18 21
Motivation
Modules, Contracts, Invariants
Tests and Test Cases
Termination:
if sqrt terminates, this function terminates.
Valid results:
if sqrt is correct then this returns correct value.
How do we handle the “if” conditions above?
Contracts
R= (R + m/R)/2
Err = abs(R*R – m)/m
Observation:
Precondition m > 0
This is required for sqrt to be correct (or may be
even to terminate).
So, quad module must guarantee before invocation
of sqrt:
disc > 0
R= (R + x/R)/2
Err = abs(R*R – x)/x
Algorithm for xy
Extract a power of 2 from y, say P.
Compute xP and multiply this to a temp. result
Repeat above steps until nothing to extract.
Termination:
Ynext is reduced by (at the least) half for each
iteration.
So, for positive y, Ynext will eventually be 0 –
because of integer division.
Pre-condition for Module xy:
y >= 0
Assumption:
pow2(x,P) returns xP if P is a power of 2.
Definition of pow2
/* Pre-condition: P = 2k for some k >= 0
Post-condition: return xP */
int pow2(int x, int P)
…
low = 1; high = N;
while (low < =high) do
mid = (low + high) /2;
if (A[mid] = = x) return x;
else if (A[mid] < x) low = mid +1;
else high = mid – 1;
endwhile;
return Not_Found;
E.g. quad
Problem Specification:
Given a, b, and c, solve quadratic equation:
a*x2 + b*x + c = 0
Solution:
// Pre-condition: b*b > 4*a*c
function quad(float a, float b, float c, boolean
sign) returns float
disc = b*b – 4*a*c;
if (sign) return (-b + sqrt(disc)) / (2 *a);
else return (-b – sqrt(disc)) / (2*a);
Exceptions
What happens when contracts are violated?
e.g. sqrt(-1)
e.g. quad(2, 1, 2, true)
- Is graceful termination guaranteed?
Exercise:
Identify test cases for function pow2(x,y) that
computes xy when y is a power of 2.
Identify test cases for function pow(x,y) that
computes xy.
Identify exception (crash) scenarios!