Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array find the second highest value

Tags:

java

I have an array contains 10 integer values. Now I want to find out the second highest number.I should not use any java API. This question was asked by one interviewer to me. He wants the logic.And his requirement is, I should not traverse through the the entire elements. Is there any way where we can achieve the result without traversing? Travesing means going through all the elements in the array. I thought for long time.Finally I gave up. If any one can explain, it would be nice. And also I asked about Sorting. He does not want the array to be sorted.

like image 835
user414967 Avatar asked Jul 19 '12 05:07

user414967


People also ask

How do you find 2nd maximum number from an array?

One of the most simple solutions can be sorting the array in ascending order and then finding the second element which is not equal to the largest element from the sorted array. So, in this way, we can find second largest element in array.

How do you find the top 2 numbers in an array?

Approach: Take two variables; let's call them first and second and mark them as -∞. Iterate through the array and for each element (let's call it current), Compare it with the first and if first is less, assign the first value to second and assign current to first.

How do you find the second highest number in an integer array in Javascript?

apply(null, arr), // get the max of the array maxi = arr. indexOf(max); arr[maxi] = -Infinity; // replace max in the array with -infinity var secondMax = Math. max. apply(null, arr); // get the new max arr[maxi] = max; return secondMax; };


1 Answers

No, it's completely impossible. If you don't look at all the data, you can't possibly know the second highest value.

You don't have to sort all the data, of course, which may be what your interviewer meant - but you do need to look at every element at least once. Every element has the possibility of changing the result, so needs to be examined.

like image 96
Jon Skeet Avatar answered Nov 05 '22 20:11

Jon Skeet