Binary
Search function from class, March 4, 2005
// Main, Fig. 11.2, p. 554
public static int
search (int[] a, int
first, int size, int target)
{
int middle;
if (size <= 0)
return -1;
else
{
middle = first
+ size/2;
if (target ==
a[middle])
return middle;
else if
(target < a[middle])
//
the target is less than a[middle],
//
so search before the middle
return search(a, first, size/2, target);
else
//
the target must be greater than a[middle],
//
so search after the middle
return search(a, middle+1, (size-1)/2, target);
}
}
Notes
from Start of Semester on Classes, Methods, and Testing
Application Programs vs. Software Components
(reusable classes)
- The user of an application program is generally an
end user, a person who's using the program to solve their problem, and
whose main concern is that the program
- does what it's supposed to do, and
- behaves predictably no matter what the input.
- The user of a reusable class is not an end user but
another programmer.
- We document application programs with user manuals;
we document classes with a list of methods, including preconditions and
postconditions for each method.
- cs1.Keyboard and java.lang.Math are software
components.
Writing Your Own ADT Classes
- Sets of reusable classes are the basis for all modern
software development, regardless of language or operating system.
- An Abstract Data Type (ADT)
class provides the necessary support for a data structure: the ability
to instantiate objects of the class, and a set of methods to manipulate
the objects.
- An object has state (a set of data values, sometimes
called fields or attributes) and behavior (a set of methods). The
methods act on the data values, which changes the state.
- The data values are usually private, so that a
calling program can't access them directly but must call methods.
- The methods are usually public, so a calling program
can use them. Sometimes there are also private methods; why would we
want these?
Characteristics of Data Values and Methods
- Public methods and data values are visible and
available to any program that imports the class; private methods and
data values are "invisible" outside the class itself and can be
directly referred to only within the class.
- A static method or data value is associated with the
class; a non-static one is associated with each object. That is, each
object has its own "copy" of the method or data value.
- A value-returning method is one that returns a value
to the calling program; a void method is one that does not return a
value. At this time we'll consider both value-returning and void
methods.