Reimplement method doSomething() so that it doesn’t modify the array. What is the cost of this new algorithm?

What will be an ideal response?


```
public static int doSomething( int array[], int n ) {
int k = 0;
// find the largest value in the range array[0] to array[n-1]
for ( int i = 1; i < n; i++ )
if ( array[i] > array[k] )
k = i;
// postcondition: array[k] is the largest value in array

int j = 0;
// find the largest value in the range array[1] to array[n]
// that is not also in position k of the array.
for ( int i = 1; i < n; i++ )
if ( array[i] > array[j] && i != k )
j = i;
// postcondition: array[j] is the SECOND largest value in array
return array[j];
}


```
The solution introduces a new variable to loop through the second time looking for the second largest value. The comments reflect this change.

The cost is the same: O(n)

Computer Science & Information Technology

You might also like to view...

The Apple iPod is a media player

Indicate whether the statement is true or false

Computer Science & Information Technology

When you hide a slide in ____ view, a slashed rectangle surrounds the slide number, which indicates the slide is hidden.

A. Slide Show B. Reading C. Normal D. Slide Sorter

Computer Science & Information Technology

How often does the AutoRecover feature save a Word document (by default)?

A) Every twenty minutes B) Every ten minutes C) Every fifteen minutes D) Every five minutes

Computer Science & Information Technology

What are photographers referring to when they say they have "good glass?"

What will be an ideal response?

Computer Science & Information Technology