Java Reference
In-Depth Information
For example, suppose that thisMethod is the name of a method you wish to time. The following statements
will compute the number of milliseconds that thisMethod requires to execute:
Date current = new Date();
// get current time
long startTime = current.getTime();
thisMethod();
// code to be timed
current = new Date();
// get current time
long stopTime = current.getTime();
long elapsedTime = stopTime - startTime; // milliseconds
1.
Write a Java program that implements the three algorithms in Figure 4-1 and times them for various values of n .
The program should display a table of the run times of each algorithm for various values of n .
2.
Consider the following two loops:
// Loop A
for (i = 1; i <= n; i++)
for (j = 1; j <= 10000; j++)
sum = sum + j;
// Loop B
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
sum = sum + j;
Although Loop A is O( n ) and Loop B is O( n 2 ), Loop B can be faster than Loop A for small values of n . Design
and implement an experiment to find a value of n for which Loop B is faster.
3.
Repeat the previous project, but use the following for Loop B:
// Loop B
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
for (k = 1; k <= n; k++)
sum = sum + k;
4.
Segment 2.12 of Chapter 2 gave the definition of the method toArray for the ADT bag, as follows:
public T[] toArray()
{
// the cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] result = (T[]) new Object[numberOfEntries]; // unchecked cast
for ( int index = 0; index < numberOfEntries; index++)
{
result[index] = bag[index];
} // end for
return result;
} // end toArray
An alternate definition calls the method Arrays.copyOf and appears as follows:
public T[] toArray()
{
return Arrays.copyOf(bag, bag.length);
} // end toArray
Compare the execution times of these two methods for bags of various sizes.
 
Search WWH ::




Custom Search