free sample here

advertisement

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

Chapter 2 Exercise Solutions

EX 2.1. What is the order of the following growth functions? a. 10n 2 + 100n + 1000 b. 10n 3 – 7 c. 2 n + 100n 3 d. n 2 log n

O(n

O(n

O(2

O(n

2

3 n

2

)

)

)

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: 2 n + 100n 3

10n 3 – 7

10n 2 + 100n + 1000

Most efficient: n 2 log n

For n = 1,000,000:

Least efficient: 2 n + 100n

10n 3 – 7

3 n 2 log n

Most efficient: 10n 2 + 100n + 1000

EX 2.3. Write the code necessary to find the largest element in an unsorted array of integers. What is the time complexity of this algorithm? int max; if (intArray.length > 0)

{ max = intArray[0]; for (int num = 1; num < intArray.length; num++) if (intArray[num] > max) max = intArray[num];

System.out.println (max);

} else

{

}

System.out.println ("The array is empty.");

The algorithm examines each of the array. If there are n elements in the array, the time complexity of the algorithm is O(n).

ScholarStock

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

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

} for (int count = 0; count < n; count ++)

{ for (int count2 = 0; count2 < n; count2 = 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

That is order n 2 .

2 + n)/ 2.

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

} for (int count = 0; count < n; count ++)

{ for (int count2 = 0; count2 < n; count2 = count2 * 2)

{

}

System.out.println(count, count2);

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

EX 2.6. Write a program that will create a table similar to the one in Figure 2.1 for any given growth function.

Solution not provided at this time.

ScholarStock

Download