How to find second largest number in an array in Java?

后端 未结 10 966
野的像风
野的像风 2021-01-01 05:57

I\'m just practicing some MIT java assignments. But, I\'m not sure how to find the second largest number. http://ocw.csail.mit.edu/f/13

  public class Marath         


        
10条回答
  •  难免孤独
    2021-01-01 06:14

    Generally speaking:

    Have two values -- "largest" and "notQuite".

    Initialize both to -9999 or whatever.

    Scan through your list. If the number is larger than "largest", set "largest" to that number. But before you do that, copy the old "largest" value to "notQuite".

    If, on the other hand, the number is smaller than "largest" but is larger than "notQuite", set "notQuite" to that number.

    When you're done examining all the numbers, "notQuite" contains the second-largest.

    And note that, as you fill in the above numbers, you can also keep a "largestIndex" and "notQuiteIndex" and fill those in with the corresponding array index values, so you can identify the "winning" value. Unfortunately, though, if there are multiple identical "largest" or "secondLargest" values the simple index scheme doesn't work and you need to keep a list of some sort.

提交回复
热议问题