From 2362bcff17ac38b0214e8e2fec25f5f527572b6c Mon Sep 17 00:00:00 2001 From: Jerry Ling Date: Tue, 26 Apr 2022 14:16:45 -0400 Subject: [PATCH] fix findmin/findmax (#93) Co-authored-by: Steven G. Johnson --- src/sparsevector.jl | 7 ++++++- test/sparsevector.jl | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/sparsevector.jl b/src/sparsevector.jl index 1f3d0793..e17ae607 100644 --- a/src/sparsevector.jl +++ b/src/sparsevector.jl @@ -1434,7 +1434,12 @@ for (fun, comp, word) in ((:findmin, :(<), "minimum"), (:findmax, :(>), "maximum # we try to avoid findfirst(iszero, x) sindex = findfirst(iszero, nzvals) # first stored zero, if any zindex = findfirst(i -> i < nzinds[i], eachindex(nzinds)) # first non-stored zero - index = isnothing(sindex) ? zindex : min(sindex, zindex) + index = if isnothing(sindex) + # non-stored zero are contiguous and at the end + isnothing(zindex) && last(nzinds) < lastindex(x) ? last(nzinds) + 1 : zindex + else + min(sindex, zindex) + end return zeroval, index end end diff --git a/test/sparsevector.jl b/test/sparsevector.jl index 6eaaba98..53b8060d 100644 --- a/test/sparsevector.jl +++ b/test/sparsevector.jl @@ -898,6 +898,24 @@ end @test_throws ArgumentError findmin(x) @test_throws ArgumentError findmax(x) end + + let v = spzeros(3) #Julia #44978 + v[1] = 2 + @test argmin(v) == 2 + @test argmax(v) == 1 + v[2] = 2 + @test argmin(v) == 3 + v[1] = 0 + v[2] = 0 + v[3] = 2 + @test argmin(v) == 1 + @test argmax(v) == 3 + end + + let v = spzeros(3) #Julia #44978 + v[3] = 2 + @test argmax(v) == 3 + end end ### linalg