braceyourself
braceyourself

Reputation: 257

Find index of largest elements

I want to find the index of each of the four largest elements in an array.

Note: - What I need is position of the elements I don't need to sort them.

Upvotes: 1

Views: 111

Answers (1)

rory.ap
rory.ap

Reputation: 35308

Loop through them and keep track of the four largest is the only way. I can't think of anything more efficient than an O(n) operation.

I think this would work. It will give you an array containing a variable number of largest indices:

Function GetLargestIndices(inArray() As Integer, numIndices As Integer) As Integer()
    ReDim returnArray(numIndices) As Integer
    Dim i As Integer
    Dim j As Integer
    Dim k As Integer

    For i = 0 To UBound(returnArray)
        returnArray(i) = -1
    Next

    For i = 0 To UBound(inArray)
        For j = UBound(returnArray) To 0 Step -1
            If (returnArray(j) = -1) Then
                returnArray(j) = i
                Exit For
            ElseIf (inArray(i) > inArray(returnArray(j))) Then
                If (j > 0) Then
                    For k = 0 To j
                        returnArray(k) = returnArray(k + 1)
                    Next
                End If

                returnArray(j) = i
                Exit For
            End If
        Next
    Next

    GetLargestIndices = returnArray
End Function

Here's a way to test it:

Sub Test()
    Dim testArray(10) As Integer

    testArray(0) = 125
    testArray(1) = 6
    testArray(2) = 45
    testArray(3) = 15
    testArray(4) = 16
    testArray(5) = 107
    testArray(6) = 108
    testArray(7) = 10
    testArray(8) = 32
    testArray(9) = 45
    testArray(10) = 72

    Dim largestArray() As Integer
    largestArray = GetLargestIndices(testArray, 4)
End Sub

Upvotes: 1

Related Questions