You are on page 1of 2

CS207, Fall 2014

Systems Development for Computational Science


Cris Cecka, Ray Jones

Paper Exercise 1
Due September 19th, In-Class! (11:59 AM ET)
(Extension students via isites dropbox)

(0) Consider the following specification and implementation for a lower bound function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

/* * Find the first element in a sorted array


* that is not less than a value .
*
* @param [ in ] a Array to search .
* @param [ in ] n The number of elements of @a a to search .
* @param [ in ] v Value to search for .
* @return An index into array @a a or @a n .
*
* @pre 0 <= @a n <= Size of @a a .
* @pre For all i , j with 0 <= i < j < n ,
*
@a a [ i ] <= @a a [ j ].
* @post For all i , j with 0 <= i < result <= j < n ,
*
@a a [ i ] < @a v <= @a a [ j ].
*
* O ( log ( n )) operations . Requires operator < for type T .
*/
template < typename T >
int lower_bound ( const T * a , int n , const T & v ) {
int low = 0;
int high = n ;
while ( low < high ) {
int mid = low + ( high - low ) / 2;
if ( a [ mid ] < v )
low = mid +1;
else
high = mid ;
}
return low ;
}

This specification is not consistent: it only requires operator< but uses <= and >= in its preand post-conditions.
More subtly, but also more importantly, it is also not minimal: there are alternative (weaker)
specifications that would allow this lower bound to be used by a wider range of inputs
inputs that the current specification prevents.
Provide a more consistent and minimal specification.

2/2

CS207: Systems Development for Computational Science

(1) In class, we abstracted lower bound to take a comparator function object rather than
always rely on operator<. In fact, its possible to define an interface to lower bound that
takes only a function object, rather than a comparator and an item to find. Write out a
complete doxygen specification comment for this lower bound. The implementation is not
required. Pay special attention to the signature and requirements of the function object.
(2) Why might the C++ standard library have implemented the version with item and
comparator, rather than the version with only a predicate?

You might also like