java - Determining Highest and Lowest Numbers in an Array -


i'm trying solve problem need write java code find 2 highest , smallest number in array given below conditions:

-every element real number

-every element random

any ideas on best approach?

you have examine every number, best algorithm linear in length of array.

the standard approach scan array, keeping track of 2 smallest , largest numbers you've seen far.

so, given firstmin, secondmin, firstmax, secondmax respectively smallest, second smallest, largest , second largest values you've seen far, on next iteration of loop:

if (value > firstmax) {     secondmax = firstmax;     firstmax = value; }  else if (value > secondmax) {     secondmax = value; }  if (value < firstmin) {     secondmin = firstmin;      firstmin = value; } else if (value < secondmin) {     secondmin = value; } 

at end of block, maintain invariant firstmin, secondmin, firstmax, secondmax respectively smallest, second smallest, largest , second largest values you've seen far. proves correctness.

this algorithm linear in length of array , examines each value once , makes minimum number of comparisons. o(1) in space, , optimal in uses 4 memory locations top , bottom 2 values.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -