← All examples

Second largest element

Go Algorithms

two maxima

Flowchart (ISO 5807)

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

Source code

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
}