# Idiomatic way to find extreme and the next (less) extreme unique values

**URL:** <https://discourse.julialang.org/t/idiomatic-way-to-find-extreme-and-the-next-less-extreme-unique-values/42331>\
**Category:** New to Julia\
**Created:** [July 1, 2020, 2:10am UTC](https://discourse.julialang.org/t/idiomatic-way-to-find-extreme-and-the-next-less-extreme-unique-values/42331 "2020-07-01T02:10:49Z")\
**Posts on this page:** 1\
**Showing post:** 10

<div class="post-metadata">

**Author:** ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)\
**Post date:** [July 1, 2020, 6:54am UTC](https://discourse.julialang.org/t/idiomatic-way-to-find-extreme-and-the-next-less-extreme-unique-values/42331/10 "2020-07-01T06:54:45Z")

</div>

Can make it quite a bit faster by moving the second if statement into the first

```julia
function twoextremas_loop2(a)
    mn,min2 = Inf,Inf
    mx,max2 = -Inf,-Inf
    for item ∈ a
        if item < mn
            min2 = mn
            mn = item
        elseif item < min2
            min2 = item
        else
            if item > mx
                max2 = mx
                mx = item
            elseif item > max2
                max2 = item
            end
        end
    end
    return (mn,mx),(min2,max2)
end

julia> @btime twoextremas($a)
  12.151 ms (2 allocations: 7.63 MiB)
((-4.722967184880966, 5.913947095464424), (-4.448884781343994, 4.541658686526455))

julia> @btime twoextremas_loop($a)
  1.469 ms (0 allocations: 0 bytes)
((-4.722967184880966, 5.913947095464424), (-4.448884781343994, 4.541658686526455))

julia> @btime twoextremas_loop2($a)
  992.839 μs (0 allocations: 0 bytes)
((-4.722967184880966, 5.913947095464424), (-4.448884781343994, 4.541658686526455))

```

---

_[View the full topic](https://discourse.julialang.org/t/idiomatic-way-to-find-extreme-and-the-next-less-extreme-unique-values/42331)._
