Skip to content

How to find 2nd Highest in an array.

Selase Kwamuar

Asked Apr 6, 2007, 11:57 AM EDT2 answers
Share
LinkedInX
Hi,

Please help me to write a code for finding the second highest in this array
1,0,4,9,6,7,8,2 using VB.Net.
Please am at a fix.

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    Code
    
    Hello,
    
    You could sort the array usig Array.Sort() and then return the element in the second position of the array.
    
    If you can't sort the array directly, just Array.Copy(...) to another array, then Array.Sort() the new array and return the element in the second position.
    
    Simon
    0
  • 0

    Try this

    Not tested but should be about right


    DIM ARR(nnnn) as long   ' this is your array with you values in it

    Dim Highest as Long
    Dim SecondHighest as long

    Dim ARRCnt as Long  ' number of elements in the array

    For I = 1 to ARRCnt -1    'if your array has 20 elements
      If ARR(I) > ARR(I + 1) then Highest = ARR(I)
    Next I

    For I = 1 to ARRCnt -1    'if your array has 20 elements
      If ARR(I) > ARR(I + 1) AND ARR(I) <> Highest then SecondHighest = ARR(I)
    Next I

    MSGBOX "Second Highest " & SecondHighest



    Another way to solve this kind of problem (without getting into complex bubble sorting routines) is to add a List Box to your Form

    Properties to be

    Visible - False
    Sorted - True

    Clear the Listbox to start with -  Listbox.Clear

    Then just keep adding data that needs sorting to the Listbox  eg,  Listbox.Additem MyData

    When finished your data is sorted top to bottom in order !

    Works a charm with alpha and numbers but beware that it actually is sorting alphabetically

    ie, 8,9,10,11,111,22222,A,B,C will end up as

    10
    11
    111
    22222
    8
    9
    A
    B
    C

    So if you want to sort numbers, make sure they are formatted, preferably zero filled

    Then if you have 000008,000009,000010,000011,000111,022222, A,B,C you will get

    000008
    000009
    000010
    000011
    000111
    022222
    A
    B
    C

    I mainly use this technique for sorting alphabetic data


    Hope that all helps

    0