Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Java Software Structures, 4th Edition Exercise Solutions, Ch.

Chapter 2 Exercise Solutions

EX 2.1. What is the order of the following growth functions?

a. 30n3 + 200n2 + 1000n + 1 O(n3)

b. 4n4 – 4 O(n4)

c. 2n + n3 + n5 O(2n)

d. n3 log n O(n3 log n)

EX 2.2. Arrange the growth functions of the previous exercise in ascending order of
efficiency for n=10 and again for n=1,000,000.
For n = 10:
Least efficient: 2n + n3 + n5
4n4 – 4
30n3 + 200n2 + 1000n + 1
Most efficient: n3 log n
For n = 1,000,000:
Least efficient: 2n + n3 + n5
4n4 – 4
n3 log n
Most efficient: 30n3 + 200n2 + 1000n + 1

EX 2.3. Write the code necessary to find the smallest element in an unsorted array of
integers. What is the time complexity of this algorithm?

int min;
if (intArray.length > 0)
{
min = intArray[0];
for (int num = 1; num < intArray.length; num++)
if (intArray[num] < min)
min = intArray[num];
System.out.println (min);
}
else
{
System.out.println ("The array is empty.");
}
The algorithm examines each of the array elements. If there are n elements in the
array, the time complexity of the algorithm is O(n).

©2014 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Java Software Structures, 4th Edition Exercise Solutions, Ch. 2

EX 2.4. Determine the growth function and order of the following code fragment:

for (int count=n; count > 0; count--)


{
for (int count2=n; count2 > 0; count2-= 2)
{
System.out.println(count + ", " + count2);
}
}

The outer loop will be executed n times. The inner loop will be executed (n+1)/2
times. Therefore, the growth function for the code fragment is n*((n+1)/2) = (n 2 +
n)/ 2. That is order n2.

EX 2.5. Determine the growth function and order of the following code fragment:

for (int count=0; count < n; count=count*10)


{
for (int count2=1; count2 < n; count2++)
{
System.out.println(count + ", " + count2);
}
}

The outer loop will be executed log 10n times. The inner loop will be executed n
times. Therefore, the growth function for the code fragment is (log 10n)*n. That is,
order n log10n.

EX 2.6. You are using an algorithm with a quadratic time complexity of n 2. How much
improvement would you expect in efficiency of the algorithm if there is a processor
speed up of 25 times?

Since the algorithm has a quadratic time complexity of n2, the processor
speed of 25 times, would increase the algorithm efficiency by the square root of
25, i.e., 5 times.

©2014 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

You might also like