Skip to content

Commit 5d761e0

Browse files
bgamarierikd
authored andcommitted
Intro.partialSort: Fix out-of-range accesses
Previously `Data.Vector.Algorithms.Intro.partialSort k v` would stumble upon undefined behavior via out-of-range array accesses if `length v < k`. Avoid this by clamping k to the length of the region being sorted.
1 parent b6f513a commit 5d761e0

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

src/Data/Vector/Algorithms/Intro.hs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,10 @@ partialSortByBounds
190190
-> m ()
191191
partialSortByBounds cmp a k l u
192192
| l >= u = return ()
193-
| otherwise = go (ilg len) l (l + k) u
193+
| otherwise = let k' = min (u-l) k
194+
-- N.B. Clamp k to the length of the range
195+
-- being sorted.
196+
in go (ilg len) l (l + k') u
194197
where
195198
isort = introsort cmp a
196199
{-# INLINE [1] isort #-}

0 commit comments

Comments
 (0)