Skip to content

Second largest element

Go two maxima

Flowchart (ISO 5807)

YesNoYesNoStartInput afirst = a[0]second = a[0]x ∈ ax > firstsecond = firstfirst = xx > second and x < firstsecond = xReturn secondEndFigure 1 — secondLargest

Source code

Go
func secondLargest(a []int) int {
    first := a[0]
    second := a[0]
    for _, x := range a {
        if x > first {
            second = first
            first = x
        } else if x > second && x < first {
            second = x
        }
    }
    return second
}

The editor opens with this code — change it and the chart redraws.

Language
Go
Constructs
two maxima
Topic
Algorithms
Formats
Word, Visio, draw.io, PDF, SVG

Related examples