diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,32 @@
+## Version 0.9.1.1 (2026-11-23)
+
+- Bump dependency upper bounds, more tests and CI improvements.
+- Make Radix instances total (mainly to appease the compiler).
+- AmericanFlag: Fix Lexicographic instance for pairs.
+- AmericanFlag: Fix pair ordering for variable-length first components.
+
+## Version 0.9.1.0 (2025-02-05)
+
+- More inlining for `sort` and `nib` functions.
+
+## Version 0.9.0.3 (2024-11-25)
+
+- Fix an off-by-one error Heap.partialSort functions.
+- Support latest ghcs.
+
+## Version 0.9.0.2 (2024-05-23)
+
+- Add `TypeOperators` pragma where needed.
+
+## Version 0.9.0.1 (2022-07-28)
+
+- Allow building with vector-0.13.*.
+
+## Version 0.9.0.0 (2022-05-19)
+
+- Add nub related functions.
+- Add sortUniq related functions (sorts, then removes duplicates).
+
 ## Version 0.8.0.4 (2020-12-06)
 
 - Fix out of range access in Intro.partialSort.
diff --git a/LICENSE b/LICENSE
--- a/LICENSE
+++ b/LICENSE
@@ -33,7 +33,7 @@
 ------------------------------------------------------------------------------
 
 The code in Data.Array.Vector.Algorithms.Mutable.Optimal is adapted from a C
-algorithm for the same purpose. The folowing is the copyright notice for said
+algorithm for the same purpose. The following is the copyright notice for said
 C code:
 
 Copyright (c) 2004 Paul Hsieh
diff --git a/bench/simple/Main.hs b/bench/simple/Main.hs
--- a/bench/simple/Main.hs
+++ b/bench/simple/Main.hs
@@ -12,7 +12,8 @@
 import Data.Ord  (comparing)
 import Data.List (maximumBy)
 
-import Data.Vector.Unboxed.Mutable
+import qualified Data.Vector.Unboxed.Mutable as UVector
+import Data.Vector.Unboxed.Mutable (MVector, Unbox)
 
 import qualified Data.Vector.Algorithms.Insertion    as INS
 import qualified Data.Vector.Algorithms.Intro        as INT
@@ -35,8 +36,8 @@
 -- Allocates a temporary buffer, like mergesort for similar purposes as noalgo.
 alloc :: (Unbox e) => MVector RealWorld e -> IO ()
 alloc arr | len <= 4  = arr `seq` return ()
-          | otherwise = (new (len `div` 2) :: IO (MVector RealWorld Int)) >> return ()
- where len = length arr
+          | otherwise = (UVector.new (len `div` 2) :: IO (MVector RealWorld Int)) >> return ()
+ where len = UVector.length arr
 
 displayTime :: String -> Integer -> IO ()
 displayTime s elapsed = putStrLn $
@@ -47,7 +48,7 @@
 
 sortSuite :: String -> GenIO -> Int -> (MVector RealWorld Int -> IO ()) -> IO ()
 sortSuite str g n sort = do
-  arr <- new n
+  arr <- UVector.new n
   putStrLn $ "Testing: " ++ str
   run "Random            " $ speedTest arr n (rand g >=> modulo n) sort
   run "Sorted            " $ speedTest arr n ascend sort
diff --git a/src/Data/Vector/Algorithms.hs b/src/Data/Vector/Algorithms.hs
new file mode 100644
--- /dev/null
+++ b/src/Data/Vector/Algorithms.hs
@@ -0,0 +1,77 @@
+{-# language BangPatterns, RankNTypes, ScopedTypeVariables #-}
+module Data.Vector.Algorithms where
+
+import Prelude hiding (length)
+import Control.Monad
+import Control.Monad.Primitive
+import Control.Monad.ST (runST)
+
+import Data.Vector.Generic.Mutable
+import qualified Data.Vector.Generic as V
+import qualified Data.Vector.Unboxed.Mutable as UMV
+import qualified Data.Bit as Bit
+
+import Data.Vector.Algorithms.Common (Comparison)
+import Data.Vector.Algorithms.Intro (sortUniqBy)
+import qualified Data.Vector.Algorithms.Search  as S
+
+-- | The `nub` function which removes duplicate elements from a vector.
+nub :: forall v e . (V.Vector v e, Ord e) => v e -> v e
+nub = nubBy compare
+{-# INLINE nub #-}
+
+-- | A version of `nub` with a custom comparison predicate.
+--
+-- /Note:/ This function makes use of `sortByUniq` using the intro
+-- sort algorithm.
+nubBy ::
+  forall v e . (V.Vector v e) =>
+  Comparison e -> v e -> v e
+nubBy cmp vec = runST $ do
+  mv <- V.unsafeThaw vec -- safe as the nubByMut algorithm copies the input
+  destMV <- nubByMut sortUniqBy cmp mv
+  v <- V.unsafeFreeze destMV
+  pure (V.force v)
+{-# INLINE nubBy #-}
+
+-- | The `nubByMut` function takes in an in-place sort algorithm
+-- and uses it to do a de-deduplicated sort. It then uses this to
+-- remove duplicate elements from the input.
+--
+-- /Note:/ Since this algorithm needs the original input and so
+-- copies before sorting in-place. As such, it is safe to use on
+-- immutable inputs.
+nubByMut ::
+  forall m v e . (PrimMonad m, MVector v e) =>
+  (Comparison e -> v (PrimState m) e -> m (v (PrimState m) e))
+  -> Comparison e -> v (PrimState m) e -> m (v (PrimState m) e)
+nubByMut alg cmp inp = do
+  let len = length inp
+  inp' <- clone inp
+  sortUniqs <- alg cmp inp'
+  let uniqLen = length sortUniqs
+  bitmask <- UMV.replicate uniqLen (Bit.Bit False) -- bitmask to track which elements have
+                                                   -- already been seen.
+  dest ::  v (PrimState m) e <- unsafeNew uniqLen  -- return vector
+  let
+    go :: Int -> Int -> m ()
+    go !srcInd !destInd
+      | srcInd == len = pure ()
+      | destInd == uniqLen = pure ()
+      | otherwise = do
+          curr    <- unsafeRead inp srcInd                -- read current element
+          sortInd <- S.binarySearchBy cmp sortUniqs curr  -- find sorted index
+          bit <- UMV.unsafeRead bitmask sortInd           -- check if we have already seen
+                                                          -- this element in bitvector
+          case bit of
+            -- if we have seen it then iterate
+            Bit.Bit True -> go (srcInd + 1) destInd
+            -- if we haven't then write it into output
+            -- and mark that it has been seen
+            Bit.Bit False -> do
+              UMV.unsafeWrite bitmask sortInd (Bit.Bit True)
+              unsafeWrite dest destInd curr
+              go (srcInd + 1) (destInd + 1)
+  go 0 0
+  pure dest
+{-# INLINABLE nubByMut #-}
diff --git a/src/Data/Vector/Algorithms/AmericanFlag.hs b/src/Data/Vector/Algorithms/AmericanFlag.hs
--- a/src/Data/Vector/Algorithms/AmericanFlag.hs
+++ b/src/Data/Vector/Algorithms/AmericanFlag.hs
@@ -27,7 +27,9 @@
 -- rather than running for a set number of iterations.
 
 module Data.Vector.Algorithms.AmericanFlag ( sort
+                                           , sortUniq
                                            , sortBy
+                                           , sortUniqBy
                                            , terminate
                                            , Lexicographic(..)
                                            ) where
@@ -206,14 +208,21 @@
     | otherwise       = fromIntegral (B.index b i) + 1
   {-# INLINE index #-}
 
+-- | Orders pairs by their first component, then their second.
+--
+-- A separator bucket, below every bucket of the first component, marks
+-- where the first component's key ends, so that pairs are ordered correctly
+-- even when the first component's 'extent' varies, as for 'B.ByteString'.
 instance (Lexicographic a, Lexicographic b) => Lexicographic (a, b) where
-  extent (a,b) = extent a + extent b
+  extent (a,b) = extent a + 1 + extent b
   {-# INLINE extent #-}
-  size _ = size (Proxy :: Proxy a) `max` size (Proxy :: Proxy b)
+  size _ = (size (Proxy :: Proxy a) + 1) `max` size (Proxy :: Proxy b)
   {-# INLINE size #-}
   index i (a,b)
-    | i >= extent a = index i b
-    | otherwise     = index i a
+    | i <  ea   = 1 + index i a
+    | i == ea   = 0
+    | otherwise = index (i - ea - 1) b
+   where ea = extent a
   {-# INLINE index #-}
 
 instance (Lexicographic a, Lexicographic b) => Lexicographic (Either a b) where
@@ -242,8 +251,16 @@
 sort v = sortBy compare terminate (size p) index v
  where p :: Proxy e
        p = Proxy
-{-# INLINABLE sort #-}
+{-# INLINE sort #-}
 
+-- | A variant on `sort` that returns a vector of unique elements.
+sortUniq :: forall e m v. (PrimMonad m, MVector v e, Lexicographic e, Ord e)
+     => v (PrimState m) e -> m (v (PrimState m) e)
+sortUniq v = sortUniqBy compare terminate (size p) index v
+ where p :: Proxy e
+       p = Proxy
+{-# INLINE sortUniq #-}
+
 -- | A fully parameterized version of the sorting algorithm. Again, this
 -- function takes both radix information and a comparison, because the
 -- algorithms falls back to insertion sort for small arrays.
@@ -261,6 +278,23 @@
                        countLoop (radix 0) v count
                        flagLoop cmp stop radix count pile v
 {-# INLINE sortBy #-}
+
+-- | A variant on `sortBy` which returns a vector of unique elements.
+sortUniqBy :: (PrimMonad m, MVector v e)
+       => Comparison e       -- ^ a comparison for the insertion sort flalback
+       -> (e -> Int -> Bool) -- ^ determines whether a stripe is complete
+       -> Int                -- ^ the number of buckets necessary
+       -> (Int -> e -> Int)  -- ^ the big-endian radix function
+       -> v (PrimState m) e  -- ^ the array to be sorted
+       -> m (v (PrimState m) e)
+sortUniqBy cmp stop buckets radix v
+  | length v == 0 = return v
+  | otherwise     = do count <- new buckets
+                       pile <- new buckets
+                       countLoop (radix 0) v count
+                       flagLoop cmp stop radix count pile v
+                       uniqueMutableBy cmp v
+{-# INLINE sortUniqBy #-}
 
 flagLoop :: (PrimMonad m, MVector v e)
          => Comparison e
diff --git a/src/Data/Vector/Algorithms/Common.hs b/src/Data/Vector/Algorithms/Common.hs
--- a/src/Data/Vector/Algorithms/Common.hs
+++ b/src/Data/Vector/Algorithms/Common.hs
@@ -1,5 +1,7 @@
 {-# LANGUAGE FlexibleContexts #-}
 {-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE ScopedTypeVariables #-}
 
 -- ---------------------------------------------------------------------------
 -- |
@@ -11,7 +13,15 @@
 --
 -- Common operations and utility functions for all sorts
 
-module Data.Vector.Algorithms.Common where
+module Data.Vector.Algorithms.Common
+  ( type Comparison
+  , copyOffset
+  , inc
+  , countLoop
+  , midPoint
+  , uniqueMutableBy
+  )
+  where
 
 import Prelude hiding (read, length)
 
@@ -57,3 +67,66 @@
     toInt :: Word -> Int
     toInt = fromIntegral
 {-# INLINE midPoint #-}
+
+-- Adapted from Andrew Martin's uniquqMutable in the primitive-sort package
+uniqueMutableBy :: forall m v a . (PrimMonad m, MVector v a)
+  => Comparison a -> v (PrimState m) a -> m (v (PrimState m) a)
+uniqueMutableBy cmp mv = do
+  let !len = basicLength mv
+  if len > 1
+    then do
+      !a0 <- unsafeRead mv 0
+      let findFirstDuplicate :: a -> Int -> m Int
+          findFirstDuplicate !prev !ix = if ix < len
+            then do
+              a <- unsafeRead mv ix
+              if cmp a prev == EQ
+                then return ix
+                else findFirstDuplicate a (ix + 1)
+            else return ix
+      dupIx <- findFirstDuplicate a0 1
+      if dupIx == len
+        then return mv
+        else do
+          let deduplicate :: a -> Int -> Int -> m Int
+              deduplicate !prev !srcIx !dstIx = if srcIx < len
+                then do
+                  a <- unsafeRead mv srcIx
+                  if cmp a prev == EQ
+                    then deduplicate a (srcIx + 1) dstIx
+                    else do
+                      unsafeWrite mv dstIx a
+                      deduplicate a (srcIx + 1) (dstIx + 1)
+                else return dstIx
+          !a <- unsafeRead mv dupIx
+          !reducedLen <- deduplicate a (dupIx + 1) dupIx
+          resizeVector mv reducedLen
+    else return mv
+{-# INLINABLE uniqueMutableBy #-}
+
+-- Used internally in uniqueMutableBy: copies the elements of a vector to one
+-- of a smaller size.
+resizeVector
+  :: (MVector v a, PrimMonad m)
+  =>  v (PrimState m) a -> Int -> m (v (PrimState m) a)
+resizeVector !src !sz = do
+  dst <- unsafeNew sz
+  copyToSmaller dst src
+  pure dst
+{-# inline resizeVector #-}
+
+-- Used internally in resizeVector: copy a vector from a larger to
+-- smaller vector. Should not be used if the source vector
+-- is smaller than the target vector.
+copyToSmaller
+  :: (MVector v a, PrimMonad m)
+  => v (PrimState m) a -> v (PrimState m) a -> m ()
+copyToSmaller !dst !src = stToPrim $ do_copy 0
+    where
+      !n = basicLength dst
+
+      do_copy i | i < n = do
+                            x <- basicUnsafeRead src i
+                            basicUnsafeWrite dst i x
+                            do_copy (i+1)
+                | otherwise = return ()
diff --git a/src/Data/Vector/Algorithms/Heap.hs b/src/Data/Vector/Algorithms/Heap.hs
--- a/src/Data/Vector/Algorithms/Heap.hs
+++ b/src/Data/Vector/Algorithms/Heap.hs
@@ -19,7 +19,9 @@
 module Data.Vector.Algorithms.Heap
        ( -- * Sorting
          sort
+       , sortUniq
        , sortBy
+       , sortUniqBy
        , sortByBounds
          -- * Selection
        , select
@@ -47,20 +49,33 @@
 
 import Data.Vector.Generic.Mutable
 
-import Data.Vector.Algorithms.Common (Comparison)
+import Data.Vector.Algorithms.Common (Comparison, uniqueMutableBy)
 
 import qualified Data.Vector.Algorithms.Optimal as O
 
 -- | Sorts an entire array using the default ordering.
 sort :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> m ()
 sort = sortBy compare
-{-# INLINABLE sort #-}
+{-# INLINE sort #-}
 
+-- | A variant on `sort` that returns a vector of unique elements.
+sortUniq :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> m (v (PrimState m) e)
+sortUniq = sortUniqBy compare
+{-# INLINE sortUniq #-}
+
 -- | Sorts an entire array using a custom ordering.
 sortBy :: (PrimMonad m, MVector v e) => Comparison e -> v (PrimState m) e -> m ()
 sortBy cmp a = sortByBounds cmp a 0 (length a)
 {-# INLINE sortBy #-}
 
+-- | A variant on `sortBy` which returns a vector of unique elements.
+sortUniqBy :: (PrimMonad m, MVector v e)
+  => Comparison e -> v (PrimState m) e -> m (v (PrimState m) e)
+sortUniqBy cmp a = do
+  sortByBounds cmp a 0 (length a)
+  uniqueMutableBy cmp a
+{-# INLINE sortUniqBy #-}
+
 -- | Sorts a portion of an array [l,u) using a custom ordering
 sortByBounds
   :: (PrimMonad m, MVector v e)
@@ -173,8 +188,8 @@
   | len == 3   = O.sort3ByOffset cmp a l
   | len == 4   = O.sort4ByOffset cmp a l
   | u <= l + k = sortByBounds cmp a l u
-  | otherwise  = do selectByBounds cmp a k l u
-                    sortHeap cmp a l (l + 4) (l + k)
+  | otherwise  = do selectByBounds cmp a (k + 1) l u
+                    sortHeap cmp a l (l + 4) (l + k + 1)
                     O.sort4ByOffset cmp a l
  where
  len = u - l
diff --git a/src/Data/Vector/Algorithms/Insertion.hs b/src/Data/Vector/Algorithms/Insertion.hs
--- a/src/Data/Vector/Algorithms/Insertion.hs
+++ b/src/Data/Vector/Algorithms/Insertion.hs
@@ -14,7 +14,9 @@
 
 module Data.Vector.Algorithms.Insertion
        ( sort
+       , sortUniq
        , sortBy
+       , sortUniqBy
        , sortByBounds
        , sortByBounds'
        , Comparison
@@ -27,19 +29,31 @@
 
 import Data.Vector.Generic.Mutable
 
-import Data.Vector.Algorithms.Common (Comparison)
+import Data.Vector.Algorithms.Common (Comparison, uniqueMutableBy)
 
 import qualified Data.Vector.Algorithms.Optimal as O
 
 -- | Sorts an entire array using the default comparison for the type
 sort :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> m ()
 sort = sortBy compare
-{-# INLINABLE sort #-}
+{-# INLINE sort #-}
 
+-- | A variant on `sort` that returns a vector of unique elements.
+sortUniq :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> m (v (PrimState m) e)
+sortUniq = sortUniqBy compare
+{-# INLINE sortUniq #-}
+
 -- | Sorts an entire array using a given comparison
 sortBy :: (PrimMonad m, MVector v e) => Comparison e -> v (PrimState m) e -> m ()
 sortBy cmp a = sortByBounds cmp a 0 (length a)
 {-# INLINE sortBy #-}
+
+-- | A variant on `sortBy` which returns a vector of unique elements.
+sortUniqBy :: (PrimMonad m, MVector v e) => Comparison e -> v (PrimState m) e -> m (v (PrimState m) e)
+sortUniqBy cmp a = do
+  sortByBounds cmp a 0 (length a)
+  uniqueMutableBy cmp a
+{-# INLINE sortUniqBy #-}
 
 -- | Sorts the portion of an array delimited by [l,u)
 sortByBounds :: (PrimMonad m, MVector v e)
diff --git a/src/Data/Vector/Algorithms/Intro.hs b/src/Data/Vector/Algorithms/Intro.hs
--- a/src/Data/Vector/Algorithms/Intro.hs
+++ b/src/Data/Vector/Algorithms/Intro.hs
@@ -35,7 +35,9 @@
 module Data.Vector.Algorithms.Intro
        ( -- * Sorting
          sort
+       , sortUniq
        , sortBy
+       , sortUniqBy
        , sortByBounds
          -- * Selecting
        , select
@@ -56,7 +58,7 @@
 import Data.Bits
 import Data.Vector.Generic.Mutable
 
-import Data.Vector.Algorithms.Common (Comparison, midPoint)
+import Data.Vector.Algorithms.Common (Comparison, midPoint, uniqueMutableBy)
 
 import qualified Data.Vector.Algorithms.Insertion as I
 import qualified Data.Vector.Algorithms.Optimal   as O
@@ -65,12 +67,25 @@
 -- | Sorts an entire array using the default ordering.
 sort :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> m ()
 sort = sortBy compare
-{-# INLINABLE sort #-}
+{-# INLINE sort #-}
 
--- | Sorts an entire array using a custom ordering.
+-- | A variant on `sort` that returns a vector of unique elements.
+sortUniq :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> m (v (PrimState m) e)
+sortUniq = sortUniqBy compare
+{-# INLINE sortUniq #-}
+
+-- | A variant on `sortBy` which returns a vector of unique elements.
 sortBy :: (PrimMonad m, MVector v e) => Comparison e -> v (PrimState m) e -> m ()
 sortBy cmp a = sortByBounds cmp a 0 (length a)
 {-# INLINE sortBy #-}
+
+-- | Sorts an entire array using a custom ordering returning a vector of
+-- the unique elements.
+sortUniqBy :: (PrimMonad m, MVector v e) => Comparison e -> v (PrimState m) e -> m (v (PrimState m) e)
+sortUniqBy cmp a = do
+  sortByBounds cmp a 0 (length a)
+  uniqueMutableBy cmp a
+{-# INLINE sortUniqBy #-}
 
 -- | Sorts a portion of an array [l,u) using a custom ordering
 sortByBounds
diff --git a/src/Data/Vector/Algorithms/Merge.hs b/src/Data/Vector/Algorithms/Merge.hs
--- a/src/Data/Vector/Algorithms/Merge.hs
+++ b/src/Data/Vector/Algorithms/Merge.hs
@@ -16,7 +16,9 @@
 
 module Data.Vector.Algorithms.Merge
        ( sort
+       , sortUniq
        , sortBy
+       , sortUniqBy
        , Comparison
        ) where
 
@@ -27,7 +29,7 @@
 import Data.Bits
 import Data.Vector.Generic.Mutable
 
-import Data.Vector.Algorithms.Common (Comparison, copyOffset, midPoint)
+import Data.Vector.Algorithms.Common (Comparison, copyOffset, midPoint, uniqueMutableBy)
 
 import qualified Data.Vector.Algorithms.Optimal   as O
 import qualified Data.Vector.Algorithms.Insertion as I
@@ -35,8 +37,13 @@
 -- | Sorts an array using the default comparison.
 sort :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> m ()
 sort = sortBy compare
-{-# INLINABLE sort #-}
+{-# INLINE sort #-}
 
+-- | A variant on `sort` that returns a vector of unique elements.
+sortUniq :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> m (v (PrimState m) e)
+sortUniq = sortUniqBy compare
+{-# INLINE sortUniq #-}
+
 -- | Sorts an array using a custom comparison.
 sortBy :: (PrimMonad m, MVector v e) => Comparison e -> v (PrimState m) e -> m ()
 sortBy cmp vec = if len <= 4
@@ -56,6 +63,13 @@
  -- odd lengths have a larger half that needs to fit, so use ceiling, not floor
  halfLen = (len + 1) `div` 2
 {-# INLINE sortBy #-}
+
+-- | A variant on `sortBy` which returns a vector of unique elements.
+sortUniqBy :: (PrimMonad m, MVector v e) => Comparison e -> v (PrimState m) e -> m (v (PrimState m) e)
+sortUniqBy cmp vec = do
+  sortBy cmp vec
+  uniqueMutableBy cmp vec
+{-# INLINE sortUniqBy #-}
 
 mergeSortWithBuf :: (PrimMonad m, MVector v e)
                  => Comparison e -> v (PrimState m) e -> v (PrimState m) e -> m ()
diff --git a/src/Data/Vector/Algorithms/Optimal.hs b/src/Data/Vector/Algorithms/Optimal.hs
--- a/src/Data/Vector/Algorithms/Optimal.hs
+++ b/src/Data/Vector/Algorithms/Optimal.hs
@@ -40,6 +40,13 @@
 
 import Data.Vector.Algorithms.Common (Comparison)
 
+#if MIN_VERSION_vector(0,13,0)
+import qualified Data.Vector.Internal.Check as Ck
+# define CHECK_INDEX(name, i, n) Ck.checkIndex Ck.Unsafe (i) (n)
+#else
+# define CHECK_INDEX(name, i, n) UNSAFE_CHECK(checkIndex) name (i) (n)
+#endif
+
 #include "vector.h"
 
 -- | Sorts the elements at the positions 'off' and 'off + 1' in the given
@@ -54,8 +61,8 @@
 -- be the 'lower' of the two.
 sort2ByIndex :: (PrimMonad m, MVector v e)
              => Comparison e -> v (PrimState m) e -> Int -> Int -> m ()
-sort2ByIndex cmp a i j = UNSAFE_CHECK(checkIndex) "sort2ByIndex" i (length a)
-                       $ UNSAFE_CHECK(checkIndex) "sort2ByIndex" j (length a) $  do
+sort2ByIndex cmp a i j = CHECK_INDEX("sort2ByIndex", i, length a)
+                       $ CHECK_INDEX("sort2ByIndex", j, length a) $  do
   a0 <- unsafeRead a i
   a1 <- unsafeRead a j
   case cmp a0 a1 of
@@ -75,9 +82,9 @@
 -- lowest position in the array.
 sort3ByIndex :: (PrimMonad m, MVector v e)
              => Comparison e -> v (PrimState m) e -> Int -> Int -> Int -> m ()
-sort3ByIndex cmp a i j k = UNSAFE_CHECK(checkIndex) "sort3ByIndex" i (length a)
-                         $ UNSAFE_CHECK(checkIndex) "sort3ByIndex" j (length a)
-                         $ UNSAFE_CHECK(checkIndex) "sort3ByIndex" k (length a) $ do
+sort3ByIndex cmp a i j k = CHECK_INDEX("sort3ByIndex", i, length a)
+                         $ CHECK_INDEX("sort3ByIndex", j, length a)
+                         $ CHECK_INDEX("sort3ByIndex", k, length a) $ do
   a0 <- unsafeRead a i
   a1 <- unsafeRead a j
   a2 <- unsafeRead a k
@@ -114,10 +121,10 @@
 -- it can be used to sort medians into particular positions and so on.
 sort4ByIndex :: (PrimMonad m, MVector v e)
              => Comparison e -> v (PrimState m) e -> Int -> Int -> Int -> Int -> m ()
-sort4ByIndex cmp a i j k l = UNSAFE_CHECK(checkIndex) "sort4ByIndex" i (length a)
-                           $ UNSAFE_CHECK(checkIndex) "sort4ByIndex" j (length a)
-                           $ UNSAFE_CHECK(checkIndex) "sort4ByIndex" k (length a)
-                           $ UNSAFE_CHECK(checkIndex) "sort4ByIndex" l (length a) $ do
+sort4ByIndex cmp a i j k l = CHECK_INDEX("sort4ByIndex", i, length a)
+                           $ CHECK_INDEX("sort4ByIndex", j, length a)
+                           $ CHECK_INDEX("sort4ByIndex", k, length a)
+                           $ CHECK_INDEX("sort4ByIndex", l, length a) $ do
   a0 <- unsafeRead a i
   a1 <- unsafeRead a j
   a2 <- unsafeRead a k
diff --git a/src/Data/Vector/Algorithms/Radix.hs b/src/Data/Vector/Algorithms/Radix.hs
--- a/src/Data/Vector/Algorithms/Radix.hs
+++ b/src/Data/Vector/Algorithms/Radix.hs
@@ -90,6 +90,7 @@
   {-# INLINE size #-}
   radix 0 e = fromIntegral (e .&. 255)
   radix 1 e = fromIntegral (((e `xor` minBound) `shiftR` 8) .&. 255)
+  radix _ _ = 0
   {-# INLINE radix #-}
 
 instance Radix Int32 where
@@ -101,6 +102,7 @@
   radix 1 e = fromIntegral ((e `shiftR` 8) .&. 255)
   radix 2 e = fromIntegral ((e `shiftR` 16) .&. 255)
   radix 3 e = fromIntegral (((e `xor` minBound) `shiftR` 24) .&. 255)
+  radix _ _ = 0
   {-# INLINE radix #-}
 
 instance Radix Int64 where
@@ -116,6 +118,7 @@
   radix 5 e = fromIntegral ((e `shiftR` 40) .&. 255)
   radix 6 e = fromIntegral ((e `shiftR` 48) .&. 255)
   radix 7 e = fromIntegral (((e `xor` minBound) `shiftR` 56) .&. 255)
+  radix _ _ = 0
   {-# INLINE radix #-}
 
 instance Radix Word where
@@ -142,6 +145,7 @@
   {-# INLINE size #-}
   radix 0 e = fromIntegral (e .&. 255)
   radix 1 e = fromIntegral ((e `shiftR` 8) .&. 255)
+  radix _ _ = 0
   {-# INLINE radix #-}
 
 instance Radix Word32 where
@@ -153,6 +157,7 @@
   radix 1 e = fromIntegral ((e `shiftR` 8) .&. 255)
   radix 2 e = fromIntegral ((e `shiftR` 16) .&. 255)
   radix 3 e = fromIntegral ((e `shiftR` 24) .&. 255)
+  radix _ _ = 0
   {-# INLINE radix #-}
 
 instance Radix Word64 where
@@ -168,6 +173,7 @@
   radix 5 e = fromIntegral ((e `shiftR` 40) .&. 255)
   radix 6 e = fromIntegral ((e `shiftR` 48) .&. 255)
   radix 7 e = fromIntegral ((e `shiftR` 56) .&. 255)
+  radix _ _ = 0
   {-# INLINE radix #-}
 
 instance (Radix i, Radix j) => Radix (i, j) where
@@ -186,7 +192,7 @@
  where
  e :: e
  e = undefined
-{-# INLINABLE sort #-}
+{-# INLINE sort #-}
 
 -- | Radix sorts an array using custom radix information
 -- requires the number of passes to fully sort the array,
diff --git a/src/Data/Vector/Algorithms/Search.hs b/src/Data/Vector/Algorithms/Search.hs
--- a/src/Data/Vector/Algorithms/Search.hs
+++ b/src/Data/Vector/Algorithms/Search.hs
@@ -119,7 +119,7 @@
  where p e' = case cmp e' e of GT -> True ; _ -> False
 {-# INLINE binarySearchRByBounds #-}
 
--- | Given a predicate that is guaraneteed to be monotone on the given vector,
+-- | Given a predicate that is guaranteed to be monotone on the given vector,
 -- finds the first index at which the predicate returns True, or the length of
 -- the array if the predicate is false for the entire array.
 binarySearchP :: (PrimMonad m, MVector v e) => (e -> Bool) -> v (PrimState m) e -> m Int
diff --git a/src/Data/Vector/Algorithms/Tim.hs b/src/Data/Vector/Algorithms/Tim.hs
--- a/src/Data/Vector/Algorithms/Tim.hs
+++ b/src/Data/Vector/Algorithms/Tim.hs
@@ -91,7 +91,9 @@
 
 module Data.Vector.Algorithms.Tim
        ( sort
+       , sortUniq
        , sortBy
+       , sortUniqBy
        ) where
 
 import Prelude hiding (length, reverse)
@@ -106,12 +108,18 @@
                                      , gallopingSearchLeftPBounds
                                      )
 import Data.Vector.Algorithms.Insertion (sortByBounds', Comparison)
+import Data.Vector.Algorithms.Common (uniqueMutableBy)
 
 -- | Sorts an array using the default comparison.
 sort :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> m ()
 sort = sortBy compare
-{-# INLINABLE sort #-}
+{-# INLINE sort #-}
 
+-- | A variant on `sort` that returns a vector of unique elements.
+sortUniq :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> m (v (PrimState m) e)
+sortUniq = sortUniqBy compare
+{-# INLINE sortUniq #-}
+
 -- | Sorts an array using a custom comparison.
 sortBy :: (PrimMonad m, MVector v e)
        => Comparison e -> v (PrimState m) e -> m ()
@@ -145,6 +153,14 @@
    merge cmp vec a b len tmpBuf >>= performRemainingMerges (a:ss)
  performRemainingMerges _ _ = return ()
 {-# INLINE sortBy #-}
+
+-- | A variant on `sortBy` which returns a vector of unique elements.
+sortUniqBy :: (PrimMonad m, MVector v e)
+       => Comparison e -> v (PrimState m) e -> m (v (PrimState m) e)
+sortUniqBy cmp vec = do
+  sortBy cmp vec
+  uniqueMutableBy cmp vec
+{-# INLINE sortUniqBy #-}
 
 -- | Computes the minimum run size for the sort. The goal is to choose a size
 -- such that there are almost if not exactly 2^n chunks of that size in the
diff --git a/tests/properties/Adversary.hs b/tests/properties/Adversary.hs
new file mode 100644
--- /dev/null
+++ b/tests/properties/Adversary.hs
@@ -0,0 +1,75 @@
+{-# LANGUAGE RankNTypes #-}
+-- The comparison functions in this module have side effects (hidden behind
+-- unsafePerformIO), so stop GHC from sharing or floating their calls.
+{-# OPTIONS_GHC -fno-cse -fno-full-laziness #-}
+
+-- | Worst-case inputs for quicksort-based algorithms, built with McIlroy's
+-- adversary ("A Killer Adversary for Quicksort", Software: Practice and
+-- Experience, 1999), and a way of counting comparisons.
+--
+-- The adversary runs the algorithm on a vector of item ids with a comparison
+-- that decides item values lazily. Items start as "gas" (larger than any
+-- decided value), and whenever two gas items are compared, one of them is
+-- frozen to the next smallest value, choosing the one that looks like the
+-- current pivot candidate. This makes every partition as unbalanced as
+-- possible. Since the algorithm is deterministic, rerunning it on the values
+-- the adversary decided reproduces exactly the same worst-case behaviour.
+module Adversary
+  ( CmpAlgo
+  , killerInput
+  , countComparisons
+  ) where
+
+import Control.Monad
+import Control.Monad.ST (ST, stToIO)
+import Data.IORef
+import System.IO.Unsafe (unsafePerformIO)
+
+import qualified Data.Vector as V
+import qualified Data.Vector.Mutable as MV
+
+-- | An in-place algorithm parameterised by its comparison.
+type CmpAlgo = forall s. (Int -> Int -> Ordering) -> MV.MVector s Int -> ST s ()
+
+-- | An input of length @n@ that drives the given algorithm into its worst
+-- case, as far as McIlroy's adversary can find one.
+killerInput :: CmpAlgo -> Int -> V.Vector Int
+killerInput algo n = unsafePerformIO $ do
+  vals      <- MV.replicate n gas
+  nsolid    <- newIORef 0
+  candidate <- newIORef 0
+  let freeze z = do s <- readIORef nsolid
+                    MV.write vals z s
+                    writeIORef nsolid (s + 1)
+      cmpIO x y = do
+        vx <- MV.read vals x
+        vy <- MV.read vals y
+        when (vx == gas && vy == gas) $ do
+          c <- readIORef candidate
+          freeze (if x == c then x else y)
+        vx' <- MV.read vals x
+        vy' <- MV.read vals y
+        if vx' == gas
+          then writeIORef candidate x
+          else when (vy' == gas) $ writeIORef candidate y
+        pure $! compare vx' vy'
+      cmp x y = unsafePerformIO (cmpIO x y)
+      {-# NOINLINE cmp #-}
+  stToIO $ V.thaw (V.enumFromN 0 n) >>= algo cmp
+  V.freeze vals
+ where
+ gas = n
+
+-- | Run the algorithm on a copy of the input, returning the number of
+-- comparisons it made and the resulting vector.
+countComparisons :: CmpAlgo -> V.Vector Int -> (Int, V.Vector Int)
+countComparisons algo v = unsafePerformIO $ do
+  count <- newIORef (0 :: Int)
+  let cmp x y = unsafePerformIO $ do modifyIORef' count (+ 1)
+                                     pure $! compare x y
+      {-# NOINLINE cmp #-}
+  r <- stToIO $ do mv <- V.thaw v
+                   algo cmp mv
+                   V.freeze mv
+  c <- readIORef count
+  pure (c, r)
diff --git a/tests/properties/Optimal.hs b/tests/properties/Optimal.hs
--- a/tests/properties/Optimal.hs
+++ b/tests/properties/Optimal.hs
@@ -8,7 +8,7 @@
 import Control.Arrow
 import Control.Monad
 
-import Data.List
+import qualified Data.List as List
 import Data.Function
 
 import Data.Vector.Generic hiding (map, zip, concatMap, (++), replicate, foldM)
@@ -32,18 +32,18 @@
 stability :: (Vector v (Int,Int)) => Int -> [v (Int, Int)]
 stability n = concatMap ( map fromList
                         . foldM interleavings []
-                        . groupBy ((==) `on` fst)
+                        . List.groupBy ((==) `on` fst)
                         . flip zip [0..])
               $ monotones (n-2) n
 
 sort2 :: (Vector v Int) => [v Int]
-sort2 = map fromList $ permutations [0,1]
+sort2 = map fromList $ List.permutations [0,1]
 
 stability2 :: (Vector v (Int,Int)) => [v (Int, Int)]
 stability2 = [fromList [(0, 0), (0, 1)]]
 
 sort3 :: (Vector v Int) => [v Int]
-sort3 = map fromList $ permutations [0..2]
+sort3 = map fromList $ List.permutations [0..2]
 
 {-
 stability3 :: [UArr (Int :*: Int)]
@@ -58,5 +58,5 @@
 -}
 
 sort4 :: (Vector v Int) => [v Int]
-sort4 = map fromList $ permutations [0..3]
+sort4 = map fromList $ List.permutations [0..3]
 
diff --git a/tests/properties/Properties.hs b/tests/properties/Properties.hs
--- a/tests/properties/Properties.hs
+++ b/tests/properties/Properties.hs
@@ -1,4 +1,7 @@
-{-# LANGUAGE RankNTypes, FlexibleContexts #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE GADTs #-}
+{-# LANGUAGE RankNTypes #-}
+{-# LANGUAGE TypeOperators #-}
 
 module Properties where
 
@@ -6,6 +9,8 @@
 
 import Optimal
 
+import Adversary
+
 import Control.Monad
 import Control.Monad.ST
 
@@ -21,9 +26,14 @@
 import Data.Vector.Generic (modify)
 
 import qualified Data.Vector.Generic.Mutable as G
+import qualified Data.Vector.Generic as GV
+import qualified Data.Vector.Primitive as PV
+import qualified Data.Vector.Storable as SV
+import qualified Data.Vector.Unboxed as UV
 
 import Data.Vector.Algorithms.Optimal (Comparison)
 import Data.Vector.Algorithms.Radix (radix, passes, size)
+import qualified Data.Vector.Algorithms as Alg
 
 import qualified Data.Map as M
 
@@ -38,6 +48,13 @@
  check e arr | V.null arr = property True
              | otherwise  = e <= V.head arr .&. check (V.head arr) (V.tail arr)
 
+prop_sorted_uniq :: (Ord e) => Vector e -> Property
+prop_sorted_uniq arr | V.length arr < 2 = property True
+                     | otherwise        = check (V.head arr) (V.tail arr)
+ where
+ check e arr | V.null arr = property True
+             | otherwise  = e < V.head arr .&. check (V.head arr) (V.tail arr)
+
 prop_empty :: (Ord e) => (forall s. MV.MVector s e -> ST s ()) -> Property
 prop_empty algo = prop_sorted (modify algo $ V.fromList [])
 
@@ -45,6 +62,23 @@
               => (forall s mv. G.MVector mv e => mv s e -> ST s ()) -> Vector e -> Property
 prop_fullsort algo arr = prop_sorted $ modify algo arr
 
+runFreeze
+  :: forall e . (Ord e)
+  => (forall s mv . G.MVector mv e => mv s e -> ST s (mv s e))
+  -> (forall s v mv. (GV.Vector v e, mv ~ GV.Mutable v) => mv s e -> ST s (v e))
+runFreeze alg mv = do
+  mv <- alg mv
+  GV.unsafeFreeze mv
+
+prop_full_sortUniq
+  :: (Ord e, Show e)
+  => (forall s . MV.MVector s e -> ST s (Vector e))
+  -> Vector e -> Property
+prop_full_sortUniq algo arr = runST $ do
+  mv <- V.unsafeThaw arr
+  arr' <- algo mv
+  pure (prop_sorted_uniq arr')
+
 {-
 prop_schwartzian :: (UA e, UA k, Ord k)
                  => (e -> k)
@@ -68,8 +102,14 @@
 prop_partialsort :: (Ord e, Arbitrary e, Show e)
                  => (forall s mv. G.MVector mv e => mv s e -> Int -> ST s ())
                  -> Positive Int -> Property
-prop_partialsort = prop_sized $ \algo k ->
-  prop_sorted . V.take k . modify algo
+prop_partialsort = prop_sized $ \algo k v -> do
+  let newVec = modify algo v
+      vhead = V.take k newVec
+      vtail = V.drop k newVec
+  prop_sorted vhead
+    .&&.
+      -- Every element in the head should be <= every element in the tail.
+      (V.null vhead || V.null vtail || V.maximum vhead <= V.minimum vtail)
 
 prop_sized_empty :: (Ord e) => (forall s. MV.MVector s e -> Int -> ST s ()) -> Property
 prop_sized_empty algo = prop_empty (flip algo 0) .&&. prop_empty (flip algo 10)
@@ -183,3 +223,392 @@
                     => (forall s. MVector s e -> e -> ST s Int)
                     -> SortedVec e -> e -> Property
 prop_search_upbound = prop_search_insert (<=) (>)
+
+prop_nub :: (Ord e, Show e) => Vector e -> Property
+prop_nub v =
+  V.fromList (nub (V.toList v)) === Alg.nub v
+
+-- | Sorting a large structured vector gives the same result as
+-- 'Data.List.sort'. This checks both sortedness and that the output is a
+-- permutation of the input, in time linear in the vector length.
+prop_large_sort :: (forall s mv. G.MVector mv Int => mv s Int -> ST s ())
+                -> LargeVec -> Property
+prop_large_sort algo (LargeVec _ v) =
+  modify algo v === V.fromList (sort (V.toList v))
+
+-- | Sorting a large structured vector of (key, original index) pairs by key
+-- gives the same result as the stable 'Data.List.sortBy'. This also checks
+-- stability.
+prop_large_stable :: (forall e s mv. G.MVector mv e => Comparison e -> mv s e -> ST s ())
+                  -> LargeVec -> Property
+prop_large_stable algo (LargeVec _ v) =
+  modify (algo (comparing fst)) kv === V.fromList (sortBy (comparing fst) (V.toList kv))
+ where
+ kv = V.imap (\i k -> (k, i)) v
+
+-- | 'sortUniq' on a large structured vector gives the sorted distinct
+-- elements.
+prop_large_sortUniq :: (forall s . MV.MVector s Int -> ST s (Vector Int))
+                    -> LargeVec -> Property
+prop_large_sortUniq algo (LargeVec _ v) = runST $ do
+  mv <- V.thaw v
+  v' <- algo mv
+  pure (v' === V.fromList (M.keys (toBag v)))
+
+-- ---------------------------------------------------------------------------
+-- Properties of the @...ByBounds@ functions
+
+-- | The elements of the result outside [l, u) are unchanged from the input.
+outsideUnchanged :: Vector Int -> Int -> Int -> Vector Int -> Property
+outsideUnchanged v l u r =
+  counterexample "elements outside [l, u) changed" $
+    V.take l r == V.take l v && V.drop u r == V.drop u v
+
+sliceList :: Int -> Int -> Vector e -> [e]
+sliceList l u = V.toList . V.slice l (u - l)
+
+prop_sortByBounds :: (forall s. MV.MVector s Int -> Int -> Int -> ST s ())
+                  -> BoundsCase -> Property
+prop_sortByBounds algo (BoundsCase v l u _) =
+  outsideUnchanged v l u r .&&. sliceList l u r === sort (sliceList l u v)
+ where
+ r = modify (\a -> algo a l u) v
+
+-- | [l, l+k) holds the k smallest elements of the input's [l, u), and
+-- [l+k, u) holds the rest.
+prop_selectByBounds :: (forall s. MV.MVector s Int -> Int -> Int -> Int -> ST s ())
+                    -> BoundsCase -> Property
+prop_selectByBounds algo (BoundsCase v l u k) =
+  outsideUnchanged v l u r
+    .&&. sort (sliceList l (l + k) r) === lo
+    .&&. sort (sliceList (l + k) u r) === hi
+ where
+ r = modify (\a -> algo a k l u) v
+ (lo, hi) = splitAt k (sort (sliceList l u v))
+
+-- | [l, l+k) holds the k smallest elements of the input's [l, u) in order,
+-- and [l+k, u) holds the rest.
+prop_partialSortByBounds :: (forall s. MV.MVector s Int -> Int -> Int -> Int -> ST s ())
+                         -> BoundsCase -> Property
+prop_partialSortByBounds algo (BoundsCase v l u k) =
+  outsideUnchanged v l u r
+    .&&. sliceList l (l + k) r === lo
+    .&&. sort (sliceList (l + k) u r) === hi
+ where
+ r = modify (\a -> algo a k l u) v
+ (lo, hi) = splitAt k (sort (sliceList l u v))
+
+-- ---------------------------------------------------------------------------
+-- Properties of the heap operations exported by Data.Vector.Algorithms.Heap.
+-- The heap is a 4-ary max-heap: the children of index i are 4i+1 .. 4i+4.
+
+isHeap :: [Int] -> Bool
+isHeap xs = and [ h V.! ((i - 1) `div` 4) >= h V.! i | i <- [1 .. V.length h - 1] ]
+ where h = V.fromList xs
+
+heapProp :: [Int] -> Property
+heapProp xs = counterexample ("not a heap: " ++ show xs) (isHeap xs)
+
+type HeapifyAlgo = forall s. MV.MVector s Int -> Int -> Int -> ST s ()
+
+-- | 'heapify' makes [l, u) a heap, without changing its elements or anything
+-- outside it.
+prop_heapify :: HeapifyAlgo -> BoundsCase -> Property
+prop_heapify heapify (BoundsCase v l u _) =
+  outsideUnchanged v l u r
+    .&&. heapProp (sliceList l u r)
+    .&&. sort (sliceList l u r) === sort (sliceList l u v)
+ where
+ r = modify (\a -> heapify a l u) v
+
+-- | Given a heap in [l, u), 'popTo' to an index t outside [l, u) moves the
+-- maximum to t and leaves a heap of the remaining elements plus the old
+-- value at t in [l, u).
+prop_popTo :: HeapifyAlgo
+           -> (forall s. MV.MVector s Int -> Int -> Int -> Int -> ST s ())
+           -> BoundsCase -> Property
+prop_popTo heapify popTo (BoundsCase v l u _) =
+  u > l && u < V.length v ==>
+    forAll (choose (u, V.length v - 1)) $ \t ->
+      let h = modify (\a -> heapify a l u) v
+          r = modify (\a -> popTo a l u t) h
+          old = sliceList l u h
+      in r V.! t === maximum old
+           .&&. heapProp (sliceList l u r)
+           .&&. sort (sliceList l u r) === sort (delete (maximum old) old ++ [h V.! t])
+           .&&. counterexample "elements outside [l, u) and t changed"
+                  (V.toList (V.take l r) == V.toList (V.take l h)
+                   && and [ r V.! i == h V.! i | i <- [u .. V.length v - 1], i /= t ])
+
+-- | Given a heap in [l, u), 'pop' with upper bound u-1 moves the maximum to
+-- u-1 and leaves a heap in [l, u-1).
+prop_pop :: HeapifyAlgo
+         -> (forall s. MV.MVector s Int -> Int -> Int -> ST s ())
+         -> BoundsCase -> Property
+prop_pop heapify pop (BoundsCase v l u _) =
+  u - l >= 1 ==>
+    outsideUnchanged v l u r
+      .&&. r V.! (u - 1) === maximum (sliceList l u v)
+      .&&. heapProp (sliceList l (u - 1) r)
+      .&&. sort (sliceList l u r) === sort (sliceList l u v)
+ where
+ r = modify (\a -> heapify a l u >> pop a l (u - 1)) v
+
+-- | Given a heap in [l, u), 'sortHeap' with l <= m < u puts the largest
+-- u-m elements, sorted, into [m, u).
+prop_sortHeap :: HeapifyAlgo
+              -> (forall s. MV.MVector s Int -> Int -> Int -> Int -> ST s ())
+              -> BoundsCase -> Property
+prop_sortHeap heapify sortHeap (BoundsCase v l u k) =
+  u > l ==>
+    let m = min (l + k) (u - 1)
+        r = modify (\a -> heapify a l u >> sortHeap a l m u) v
+        sorted = sort (sliceList l u v)
+    in outsideUnchanged v l u r
+         .&&. sliceList m u r === drop (m - l) sorted
+         .&&. sort (sliceList l u r) === sorted
+
+-- | Building a heap by repeated 'heapInsert' gives a heap of the inserted
+-- elements.
+prop_heapInsert :: (forall s. MV.MVector s Int -> Int -> Int -> Int -> ST s ())
+                -> LargeVec -> Property
+prop_heapInsert heapInsert (LargeVec _ v) =
+  heapProp (V.toList r) .&&. sort (V.toList r) === sort (V.toList v)
+ where
+ r = runST $ do
+   a <- MV.new (V.length v)
+   V.imapM_ (\i e -> heapInsert a 0 i e) v
+   V.freeze a
+
+-- ---------------------------------------------------------------------------
+-- Worst-case inputs for introsort
+
+-- | On an input built by McIlroy's adversary for this algorithm, the result
+-- is correct and the number of comparisons stays within 6 n lg n.
+--
+-- Without introsort's heap sort fallback these inputs need about n^2/4
+-- comparisons, which exceeds the bound for every n >= 500 tested here, so
+-- this checks that the fallback works. With it, the observed count is at
+-- most about 3.9 n lg n.
+prop_killer :: CmpAlgo -> (Vector Int -> Vector Int -> Property) -> Property
+prop_killer algo correct = forAll (choose (500, 5000)) $ \n ->
+  let input  = killerInput algo n
+      (c, r) = countComparisons algo input
+      bound  = 6 * fromIntegral n * logBase 2 (fromIntegral n) :: Double
+  in correct input r
+       .&&. counterexample ("n = " ++ show n ++ ": " ++ show c
+                            ++ " comparisons exceeds 6 n lg n = " ++ show (round bound :: Int))
+              (fromIntegral c <= bound)
+
+-- | The result is the sorted input.
+resultSorted :: Vector Int -> Vector Int -> Property
+resultSorted input r = r === V.fromList (sort (V.toList input))
+
+-- | The first half of the result holds the smallest half of the input, in
+-- order if @ordered@ is set.
+resultHalf :: Bool -> Vector Int -> Vector Int -> Property
+resultHalf ordered input r =
+  (if ordered then front else sort front) === lo .&&. sort back === hi
+ where
+ k = V.length input `div` 2
+ (front, back) = splitAt k (V.toList r)
+ (lo, hi) = splitAt k (sort (V.toList input))
+
+-- ---------------------------------------------------------------------------
+-- Sorting large vectors of other element types
+
+-- | Like 'prop_large_sort', but first maps the 'Int' keys to another element
+-- type. Mapping with a function that has few distinct values in its first
+-- component gives large groups of elements that only differ later on.
+prop_large_sort_via :: (Ord e, Show e)
+                    => (Int -> e)
+                    -> (forall s mv. G.MVector mv e => mv s e -> ST s ())
+                    -> LargeVec -> Property
+prop_large_sort_via f algo (LargeVec _ v) =
+  modify algo w === V.fromList (sort (V.toList w))
+ where
+ w = V.map f v
+
+-- ---------------------------------------------------------------------------
+-- Searching
+
+type PSearchBounds = forall s. (Int -> Bool) -> MV.MVector s Int -> Int -> Int -> ST s Int
+type CmpSearchBounds = forall s. MV.MVector s Int -> Int -> Int -> Int -> ST s Int
+
+runSearch :: Vector Int -> (forall s. MV.MVector s Int -> ST s Int) -> Int
+runSearch v search = runST (V.thaw v >>= search)
+
+-- | The index in [l, u] at which a monotone predicate turns from False to
+-- True on the sorted range [l, u), or u if it is False throughout.
+modelP :: (Int -> Bool) -> Vector Int -> Int -> Int -> Int
+modelP p v l u = l + length (takeWhile (not . p) (sliceList l u v))
+
+-- | A predicate search over [l, u) agrees with the model, for the monotone
+-- predicates (>= e) and (> e).
+prop_searchPBounds :: PSearchBounds -> SearchCase -> Property
+prop_searchPBounds search (SearchCase v l u e) = conjoin
+  [ counterexample name $ runSearch v (\a -> search p a l u) === modelP p v l u
+  | (name, p) <- [(">= e", (>= e)), ("> e", (> e))] ]
+
+-- | A predicate search over the whole vector agrees with the model.
+prop_searchP :: (forall s. (Int -> Bool) -> MV.MVector s Int -> ST s Int)
+             -> SearchCase -> Property
+prop_searchP search (SearchCase v _ _ e) = conjoin
+  [ counterexample name $ runSearch v (search p) === modelP p v 0 (V.length v)
+  | (name, p) <- [(">= e", (>= e)), ("> e", (> e))] ]
+
+-- | 'binarySearchLByBounds' finds the first index in [l, u] at which e can be
+-- inserted, and 'binarySearchRByBounds' the last.
+prop_searchLBounds, prop_searchRBounds :: CmpSearchBounds -> SearchCase -> Property
+prop_searchLBounds search (SearchCase v l u e) =
+  runSearch v (\a -> search a e l u) === modelP (>= e) v l u
+prop_searchRBounds search (SearchCase v l u e) =
+  runSearch v (\a -> search a e l u) === modelP (> e) v l u
+
+-- | 'binarySearchByBounds' finds some index in [l, u] at which e can be
+-- inserted while keeping [l, u) sorted.
+prop_searchAnyBounds :: CmpSearchBounds -> SearchCase -> Property
+prop_searchAnyBounds search (SearchCase v l u e) =
+  counterexample ("result " ++ show i) $
+    modelP (>= e) v l u <= i && i <= modelP (> e) v l u
+ where
+ i = runSearch v (\a -> search a e l u)
+
+-- ---------------------------------------------------------------------------
+-- Optimal sorts at arbitrary indices
+
+-- | A @sortNByIndex@ function from "Data.Vector.Algorithms.Optimal", taking
+-- its n indices as a list.
+type ByIndexAlgo = forall s. [Int] -> MV.MVector s (Int, Int) -> ST s ()
+
+-- | Placing n elements at distinct positions of a larger vector, given in
+-- any order, and sorting them by index: read back in the order of the
+-- indices, the elements are stably sorted (by their first component), and
+-- every other position is unchanged. This is checked for every permutation
+-- of n distinct keys and every input in the exhaustive stability set.
+prop_optimal_byIndex :: Int -> ByIndexAlgo -> Property
+prop_optimal_byIndex n algo =
+  forAll (choose (n, 20)) $ \len ->
+  forAll (take n <$> shuffle [0 .. len - 1]) $ \ixs ->
+    conjoin [ check len ixs (V.toList xs) | xs <- inputs ]
+ where
+ inputs :: [Vector (Int, Int)]
+ inputs = map (\p -> V.fromList (zip p [0 ..])) (permutations [0 .. n - 1])
+            ++ stability n
+ check len ixs xs =
+   let filler = V.generate len (\i -> (-1, -1 - i))
+       before = filler V.// zip ixs xs
+       after  = modify (algo ixs) before
+       others = [ i | i <- [0 .. len - 1], i `notElem` ixs ]
+   in counterexample ("indices " ++ show ixs ++ ", input " ++ show xs) $
+        map (after V.!) ixs === sortBy (comparing fst) xs
+          .&&. counterexample "positions outside the indices changed"
+                 (map (after V.!) others == map (before V.!) others)
+
+-- ---------------------------------------------------------------------------
+-- nub
+
+type SortUniqBy = forall s. Comparison Int -> MV.MVector s Int -> ST s (MV.MVector s Int)
+
+-- | The first element of each equivalence class, in the order of the input,
+-- for a comparison that is 'compare' on the given key.
+firstOccurrencesOn :: (Int -> Int) -> [Int] -> [Int]
+firstOccurrencesOn key = go M.empty
+ where
+ go _ [] = []
+ go seen (x:xs)
+   | M.member (key x) seen = go seen xs
+   | otherwise             = x : go (M.insert (key x) () seen) xs
+
+-- | The comparisons nub is tested with, as a name, the comparison, and the
+-- key it compares on (the descending comparison has the same classes as
+-- 'compare').
+nubComparisons :: [(String, Comparison Int, Int -> Int)]
+nubComparisons =
+  [ ("compare",       compare,                id)
+  , ("descending",    flip compare,           id)
+  , ("modulo 7",      comparing (`mod` 7),    (`mod` 7))
+  , ("absolute",      comparing abs,          abs)
+  ]
+
+-- | 'Alg.nubByMut' with the given sortUniqBy keeps the first element of each
+-- equivalence class in input order, and leaves its input unchanged.
+prop_nubByMut :: SortUniqBy -> Vector Int -> Property
+prop_nubByMut alg v = conjoin
+  [ counterexample name $
+      let (r, v') = runST $ do
+            mv <- V.thaw v
+            d  <- Alg.nubByMut alg cmp mv
+            (,) <$> V.freeze d <*> V.freeze mv
+      in V.toList r === firstOccurrencesOn key (V.toList v)
+           .&&. counterexample "input changed" (v' == v)
+  | (name, cmp, key) <- nubComparisons ]
+
+-- | 'Alg.nubBy' keeps the first element of each equivalence class in input
+-- order.
+prop_nubBy :: Vector Int -> Property
+prop_nubBy v = conjoin
+  [ counterexample name $
+      V.toList (Alg.nubBy cmp v) === firstOccurrencesOn key (V.toList v)
+  | (name, cmp, key) <- nubComparisons ]
+
+-- ---------------------------------------------------------------------------
+-- Other vector types
+--
+-- The algorithms are INLINE and get specialised to each vector type, so
+-- also run them on unboxed, storable and primitive vectors, not just the
+-- boxed vectors used everywhere else.
+
+type GenAlgo = forall s mv. G.MVector mv Int => mv s Int -> ST s ()
+type GenUniqAlgo = forall s mv. G.MVector mv Int => mv s Int -> ST s (mv s Int)
+
+-- | Run an in-place algorithm on the input converted to each of the other
+-- vector types, and check each result with the given property.
+prop_vector_types :: GenAlgo -> (Vector Int -> Vector Int -> Property)
+                  -> Vector Int -> Property
+prop_vector_types algo correct v = conjoin
+  [ counterexample "unboxed"   $ correct v (via (undefined :: UV.Vector Int))
+  , counterexample "storable"  $ correct v (via (undefined :: SV.Vector Int))
+  , counterexample "primitive" $ correct v (via (undefined :: PV.Vector Int))
+  ]
+ where
+ via :: GV.Vector w Int => w Int -> Vector Int
+ via proxy = GV.convert (GV.modify algo (GV.convert v `asTypeOf` proxy))
+
+-- | 'prop_vector_types' for algorithms returning a vector of unique
+-- elements: the result is the sorted distinct elements of the input.
+prop_vector_types_uniq :: GenUniqAlgo -> Vector Int -> Property
+prop_vector_types_uniq algo v = conjoin
+  [ counterexample "unboxed"   $ via (undefined :: UV.Vector Int) === expected
+  , counterexample "storable"  $ via (undefined :: SV.Vector Int) === expected
+  , counterexample "primitive" $ via (undefined :: PV.Vector Int) === expected
+  ]
+ where
+ expected = M.keys (toBag v)
+ via :: GV.Vector w Int => w Int -> [Int]
+ via proxy = runST $ do
+   mv <- GV.thaw (GV.convert v `asTypeOf` proxy)
+   r  <- algo mv
+   GV.toList . (`asTypeOf` proxy) <$> GV.freeze r
+
+-- | A stable sort is stable on unboxed vectors of (key, original index)
+-- pairs.
+prop_stable_unboxed :: (forall s mv. G.MVector mv (Int, Int)
+                          => Comparison (Int, Int) -> mv s (Int, Int) -> ST s ())
+                    -> LargeVec -> Property
+prop_stable_unboxed algo (LargeVec _ v) =
+  UV.toList (GV.modify (algo (comparing fst)) kv)
+    === sortBy (comparing fst) (UV.toList kv)
+ where
+ kv = UV.imap (\i k -> (k, i)) (UV.convert v)
+
+-- | 'Alg.nub' on each of the other vector types keeps the first occurrence
+-- of each element, in input order.
+prop_nub_vector_types :: Vector Int -> Property
+prop_nub_vector_types v = conjoin
+  [ counterexample "unboxed"   $ UV.toList (Alg.nub (UV.convert v)) === expected
+  , counterexample "storable"  $ SV.toList (Alg.nub (SV.convert v)) === expected
+  , counterexample "primitive" $ PV.toList (Alg.nub (PV.convert v)) === expected
+  ]
+ where
+ expected = firstOccurrencesOn id (V.toList v)
diff --git a/tests/properties/Tests.hs b/tests/properties/Tests.hs
--- a/tests/properties/Tests.hs
+++ b/tests/properties/Tests.hs
@@ -1,24 +1,34 @@
-{-# LANGUAGE RankNTypes, TypeOperators, FlexibleContexts #-}
+{-# LANGUAGE RankNTypes, TypeOperators, FlexibleContexts, TypeApplications #-}
 
 module Main (main) where
 
 import Properties
 
+import Adversary (CmpAlgo)
+
 import Util
 
-import Test.QuickCheck
+import Test.QuickCheck hiding (quickCheck, quickCheckWith)
+import qualified Test.QuickCheck as QC
 
+import Data.IORef
+import System.Exit (exitFailure)
+import System.IO.Unsafe (unsafePerformIO)
+
 import Control.Monad
 import Control.Monad.ST
 
 import Data.Int
 import Data.Word
+import Data.Ord (Down (..), comparing)
 
 import qualified Data.ByteString as B
 
 import Data.Vector (Vector)
 import qualified Data.Vector as V
+import qualified Data.Vector.Mutable as BoxedMV
 
+import qualified Data.Vector.Generic as G
 import Data.Vector.Generic.Mutable (MVector)
 import qualified Data.Vector.Generic.Mutable as MV
 
@@ -36,10 +46,12 @@
 type Algo      e r = forall s mv. MVector mv e => mv s e -> ST s r
 type SizeAlgo  e r = forall s mv. MVector mv e => mv s e -> Int -> ST s r
 type BoundAlgo e r = forall s mv. MVector mv e => mv s e -> Int -> Int -> ST s r
+type MonoAlgo  e r = forall s . BoxedMV.MVector s e -> ST s r
 
 newtype WrappedAlgo      e r = WrapAlgo      { unWrapAlgo      :: Algo      e r }
 newtype WrappedSizeAlgo  e r = WrapSizeAlgo  { unWrapSizeAlgo  :: SizeAlgo  e r }
 newtype WrappedBoundAlgo e r = WrapBoundAlgo { unWrapBoundAlgo :: BoundAlgo e r }
+newtype WrappedMonoAlgo  e r = MonoAlgo      { unWrapMonoAlgo  :: MonoAlgo  e r }
 
 args = stdArgs
        { maxSuccess = 1000
@@ -57,6 +69,18 @@
          , ("timsort", WrapAlgo T.sort)
          ]
 
+check_Int_sortUniq = forM_ algos $ \(name,algo) ->
+  quickCheckWith args (label name . prop_full_sortUniq (unWrapMonoAlgo algo))
+ where
+ algos :: [(String, WrappedMonoAlgo Int (Vector Int))]
+ algos = [ ("intro_sortUniq", MonoAlgo (runFreeze INT.sortUniq))
+         , ("insertion sortUniq", MonoAlgo (runFreeze INS.sortUniq))
+         , ("merge sortUniq", MonoAlgo (runFreeze M.sortUniq))
+         , ("heap_sortUniq", MonoAlgo (runFreeze H.sortUniq))
+         , ("tim_sortUniq", MonoAlgo (runFreeze T.sortUniq))
+         , ("flag_sortUniq", MonoAlgo (runFreeze AF.sortUniq))
+         ]
+
 check_Int_partialsort = forM_ algos $ \(name,algo) ->
   quickCheckWith args (label name . prop_partialsort (unWrapSizeAlgo algo))
  where
@@ -73,6 +97,179 @@
          , ("heap select", WrapSizeAlgo H.select)
          ]
 
+check_large = do
+  forM_ sorts $ \(name, algo) ->
+    qc (label name . prop_large_sort (unWrapAlgo algo))
+  qc (label "merge sort stable" . prop_large_stable M.sortBy)
+  qc (label "timsort stable" . prop_large_stable T.sortBy)
+  forM_ uniqs $ \(name, algo) ->
+    qc (label name . prop_large_sortUniq (unWrapMonoAlgo algo))
+ where
+ qc = quickCheckWith args { maxSuccess = 300 }
+ sorts :: [(String, WrappedAlgo Int ())]
+ sorts = [ ("introsort", WrapAlgo INT.sort)
+         , ("merge sort", WrapAlgo M.sort)
+         , ("heapsort", WrapAlgo H.sort)
+         , ("timsort", WrapAlgo T.sort)
+         , ("radix sort", WrapAlgo R.sort)
+         , ("american flag sort", WrapAlgo AF.sort)
+         ]
+ uniqs :: [(String, WrappedMonoAlgo Int (Vector Int))]
+ uniqs = [ ("intro sortUniq", MonoAlgo (runFreeze INT.sortUniq))
+         , ("merge sortUniq", MonoAlgo (runFreeze M.sortUniq))
+         , ("heap sortUniq", MonoAlgo (runFreeze H.sortUniq))
+         , ("tim sortUniq", MonoAlgo (runFreeze T.sortUniq))
+         , ("flag sortUniq", MonoAlgo (runFreeze AF.sortUniq))
+         ]
+
+check_bounds = do
+  qc (label "intro sortByBounds"     . prop_sortByBounds (INT.sortByBounds compare))
+  qc (label "heap sortByBounds"      . prop_sortByBounds (H.sortByBounds compare))
+  qc (label "insertion sortByBounds" . prop_sortByBounds (INS.sortByBounds compare))
+  qc (label "intro selectByBounds"   . prop_selectByBounds (INT.selectByBounds compare))
+  qc (label "heap selectByBounds"    . prop_selectByBounds (H.selectByBounds compare))
+  qc (label "intro partialSortByBounds" . prop_partialSortByBounds (INT.partialSortByBounds compare))
+  qc (label "heap partialSortByBounds"  . prop_partialSortByBounds (H.partialSortByBounds compare))
+ where
+ qc = quickCheckWith args { maxSuccess = 500 }
+
+check_heap_ops = do
+  qc (label "heapify"    . prop_heapify heapify)
+  qc (label "pop"        . prop_pop heapify (H.pop compare))
+  qc (label "popTo"      . prop_popTo heapify (H.popTo compare))
+  qc (label "sortHeap"   . prop_sortHeap heapify (H.sortHeap compare))
+  qc (label "heapInsert" . prop_heapInsert (H.heapInsert compare))
+ where
+ qc :: Testable prop => prop -> IO ()
+ qc = quickCheckWith args { maxSuccess = 500 }
+ heapify :: HeapifyAlgo
+ heapify = H.heapify compare
+
+check_killer = do
+  qc "intro sort"         (\cmp a -> INT.sortBy cmp a) resultSorted
+  qc "intro select"       (\cmp a -> INT.selectBy cmp a (half a)) (resultHalf False)
+  qc "intro partial sort" (\cmp a -> INT.partialSortBy cmp a (half a)) (resultHalf True)
+ where
+ qc :: String -> CmpAlgo -> (Vector Int -> Vector Int -> Property) -> IO ()
+ qc name algo correct = quickCheckWith args { maxSuccess = 50 } (label name (prop_killer algo correct))
+ half a = MV.length a `div` 2
+
+check_flag_compound = do
+  -- Few distinct first components, so that large groups of elements are
+  -- distinguished only by their second component.
+  qc "flag (Word8, Word8)"   $ prop_large_sort_via (\x -> (w8 (x `mod` 3), w8 x)) AF.sort
+  qc "flag (Word16, Word16)" $ prop_large_sort_via (\x -> (w16 (x `mod` 3), w16 x)) AF.sort
+  qc "flag (Int, Int)"       $ prop_large_sort_via (\x -> (x `mod` 3, x)) AF.sort
+  qc "flag (Word8, Int)"     $ prop_large_sort_via (\x -> (w8 (x `mod` 3), x)) AF.sort
+  qc "flag (Int, Word8)"     $ prop_large_sort_via (\x -> (x `mod` 3, w8 x)) AF.sort
+  qc "flag Either"           $ prop_large_sort_via
+                                 (\x -> if even x then Left (w16 (x `div` 7)) else Right x) AF.sort
+  qc "flag (ByteString, Int)" $ prop_large_sort_via
+                                 (\x -> (B.pack [fromIntegral (x `mod` 3)], x)) AF.sort
+  -- First components of varying length, sharing prefixes, so that one
+  -- element's first component can end where another's continues.
+  qc "flag (variable ByteString, Int)" $ prop_large_sort_via (\x -> (varBytes x, x)) AF.sort
+  qc "flag ((Int, variable ByteString), Int)" $
+       prop_large_sort_via (\x -> ((x `mod` 2, varBytes x), x)) AF.sort
+  -- A custom radix and comparison that sort into descending order.
+  qc "flag sortBy descending" $ prop_large_sort_via (Down . w32)
+       (AF.sortBy compare (\(Down e) i -> AF.terminate e i) 256
+                  (\i (Down e) -> 255 - AF.index i e))
+ where
+ qc :: Testable prop => String -> prop -> IO ()
+ qc name = quickCheckWith args { maxSuccess = 300 } . label name
+ w8 :: Int -> Word8
+ w8 = fromIntegral
+ w16 :: Int -> Word16
+ w16 = fromIntegral
+ w32 :: Int -> Word32
+ w32 = fromIntegral
+ -- 0 to 3 bytes, drawn from few values (including 0 and 255).
+ varBytes :: Int -> B.ByteString
+ varBytes x = B.pack . take (x `mod` 4) $
+                map (\d -> [0, 1, 97, 255] !! ((x `div` d) `mod` 4)) [4, 16, 64]
+
+check_search = do
+  qc "binarySearchPBounds"         $ prop_searchPBounds SR.binarySearchPBounds
+  qc "gallopingSearchLeftPBounds"  $ prop_searchPBounds SR.gallopingSearchLeftPBounds
+  qc "gallopingSearchRightPBounds" $ prop_searchPBounds SR.gallopingSearchRightPBounds
+  qc "binarySearchP"               $ prop_searchP SR.binarySearchP
+  qc "gallopingSearchLeftP"        $ prop_searchP SR.gallopingSearchLeftP
+  qc "gallopingSearchRightP"       $ prop_searchP SR.gallopingSearchRightP
+  qc "binarySearchLByBounds"       $ prop_searchLBounds (SR.binarySearchLByBounds compare)
+  qc "binarySearchRByBounds"       $ prop_searchRBounds (SR.binarySearchRByBounds compare)
+  qc "binarySearchByBounds"        $ prop_searchAnyBounds (SR.binarySearchByBounds compare)
+ where
+ qc :: Testable prop => String -> prop -> IO ()
+ qc name = quickCheckWith args { maxSuccess = 1000 } . label name
+
+check_vector_types = do
+  forM_ sorts $ \(name, algo) -> do
+    qc name (prop_vector_types (unWrapAlgo algo) resultSorted)
+    qc (name ++ " large") (\(LargeVec _ v) -> prop_vector_types (unWrapAlgo algo) resultSorted v)
+  -- Insertion sort is quadratic, so only test it on small vectors.
+  qc "insertion sort" (prop_vector_types INS.sort resultSorted)
+  forM_ uniqs $ \(name, algo) -> do
+    qc name (prop_vector_types_uniq (unWrapUniq algo))
+    qc (name ++ " large") (\(LargeVec _ v) -> prop_vector_types_uniq (unWrapUniq algo) v)
+  qc "insertion sortUniq" (prop_vector_types_uniq INS.sortUniq)
+  forM_ halves $ \(name, ordered, algo) ->
+    qc (name ++ " large")
+       (\(LargeVec _ v) -> prop_vector_types (\a -> unWrapSizeAlgo algo a (half a)) (resultHalf ordered) v)
+  qc "merge sort stable unboxed" (prop_stable_unboxed M.sortBy)
+  qc "timsort stable unboxed"    (prop_stable_unboxed T.sortBy)
+  qc "nub"       prop_nub_vector_types
+  qc "nub large" (\(LargeVec _ v) -> prop_nub_vector_types v)
+ where
+ qc :: Testable prop => String -> prop -> IO ()
+ qc name = quickCheckWith args { maxSuccess = 200 } . label name
+ half a = MV.length a `div` 2
+ sorts :: [(String, WrappedAlgo Int ())]
+ sorts = [ ("introsort", WrapAlgo INT.sort)
+         , ("merge sort", WrapAlgo M.sort)
+         , ("heapsort", WrapAlgo H.sort)
+         , ("timsort", WrapAlgo T.sort)
+         , ("radix sort", WrapAlgo R.sort)
+         , ("american flag sort", WrapAlgo AF.sort)
+         ]
+ uniqs :: [(String, WrappedUniq)]
+ uniqs = [ ("intro sortUniq", WrapUniq INT.sortUniq)
+         , ("merge sortUniq", WrapUniq M.sortUniq)
+         , ("heap sortUniq", WrapUniq H.sortUniq)
+         , ("tim sortUniq", WrapUniq T.sortUniq)
+         , ("flag sortUniq", WrapUniq AF.sortUniq)
+         ]
+ halves :: [(String, Bool, WrappedSizeAlgo Int ())]
+ halves = [ ("intro select", False, WrapSizeAlgo INT.select)
+          , ("heap select", False, WrapSizeAlgo H.select)
+          , ("intro partialSort", True, WrapSizeAlgo INT.partialSort)
+          , ("heap partialSort", True, WrapSizeAlgo H.partialSort)
+          ]
+
+newtype WrappedUniq = WrapUniq { unWrapUniq :: GenUniqAlgo }
+
+check_nub = do
+  quickCheckWith args (label "nub Int" . (prop_nub @Int))
+  qc "nubBy"       prop_nubBy
+  qc "nubBy large" (\(LargeVec _ v) -> prop_nubBy v)
+  forM_ sortUniqs $ \(name, alg) -> do
+    qc ("nubByMut " ++ name) (prop_nubByMut (unWrapSortUniqBy alg))
+    qc ("nubByMut " ++ name ++ " large") (\(LargeVec _ v) -> prop_nubByMut (unWrapSortUniqBy alg) v)
+  -- Insertion sort is quadratic, so only test it on small vectors.
+  qc "nubByMut insertion" (prop_nubByMut INS.sortUniqBy)
+ where
+ qc :: Testable prop => String -> prop -> IO ()
+ qc name = quickCheckWith args { maxSuccess = 300 } . label name
+ sortUniqs :: [(String, WrappedSortUniqBy)]
+ sortUniqs = [ ("intro", WrapSortUniqBy INT.sortUniqBy)
+             , ("merge", WrapSortUniqBy M.sortUniqBy)
+             , ("heap",  WrapSortUniqBy H.sortUniqBy)
+             , ("tim",   WrapSortUniqBy T.sortUniqBy)
+             ]
+
+newtype WrappedSortUniqBy = WrapSortUniqBy { unWrapSortUniqBy :: SortUniqBy }
+
+
 check_radix_sorts = do
   qc (label "radix Word8"       . prop_fullsort (R.sort :: Algo Word8  ()))
   qc (label "radix Word16"      . prop_fullsort (R.sort :: Algo Word16 ()))
@@ -108,7 +305,8 @@
  i2w = fromIntegral
 -}
 
-check_stable = do quickCheckWith args (label "merge sort" . prop_stable M.sortBy)
+check_stable = do quickCheckWith args (label "insertion sort" . prop_stable INS.sortBy)
+                  quickCheckWith args (label "merge sort" . prop_stable M.sortBy)
                   quickCheckWith args (label "radix sort" . prop_stable_radix R.sortBy)
                   quickCheckWith args (label "tim sort" . prop_stable T.sortBy)
 
@@ -116,10 +314,23 @@
 check_optimal = do qc . label "size 2" $ prop_optimal 2 O.sort2ByOffset
                    qc . label "size 3" $ prop_optimal 3 O.sort3ByOffset
                    qc . label "size 4" $ prop_optimal 4 O.sort4ByOffset
+                   qcIx . label "size 2 by index" $ prop_optimal_byIndex 2 sort2
+                   qcIx . label "size 3 by index" $ prop_optimal_byIndex 3 sort3
+                   qcIx . label "size 4 by index" $ prop_optimal_byIndex 4 sort4
  where
  qc = quickCheck
+ qcIx :: Property -> IO ()
+ qcIx = quickCheckWith args { maxSuccess = 500 }
+ sort2, sort3, sort4 :: ByIndexAlgo
+ sort2 ixs a = case ixs of [i, j]       -> O.sort2ByIndex (comparing fst) a i j
+                           _            -> error "sort2: expected 2 indices"
+ sort3 ixs a = case ixs of [i, j, k]    -> O.sort3ByIndex (comparing fst) a i j k
+                           _            -> error "sort3: expected 3 indices"
+ sort4 ixs a = case ixs of [i, j, k, l] -> O.sort4ByIndex (comparing fst) a i j k l
+                           _            -> error "sort4: expected 4 indices"
 
 check_permutation = do
+  qc $ label "insertion"    . prop_permutation (INS.sort :: Algo Int ())
   qc $ label "introsort"    . prop_permutation (INT.sort :: Algo Int ())
   qc $ label "heapsort"     . prop_permutation (H.sort :: Algo Int ())
 
@@ -135,6 +346,7 @@
   qc $ label "radix W32"    . prop_permutation (R.sort :: Algo Word32 ())
   qc $ label "radix W64"    . prop_permutation (R.sort :: Algo Word64 ())
   qc $ label "radix Word"   . prop_permutation (R.sort :: Algo Word   ())
+  qc $ label "radix (Int, Int)" . prop_permutation (R.sort :: Algo (Int, Int) ())
   qc $ label "flag I8"      . prop_permutation (AF.sort :: Algo Int8   ())
   qc $ label "flag I16"     . prop_permutation (AF.sort :: Algo Int16  ())
   qc $ label "flag I32"     . prop_permutation (AF.sort :: Algo Int32  ())
@@ -159,6 +371,7 @@
  qc prop = quickCheckWith args prop
 
 check_corners = do
+  qc "insertion empty"    $ prop_empty       (INS.sort        :: Algo Int ())
   qc "introsort empty"    $ prop_empty       (INT.sort        :: Algo Int ())
   qc "intropartial empty" $ prop_sized_empty (INT.partialSort :: SizeAlgo Int ())
   qc "introselect empty"  $ prop_sized_empty (INT.select      :: SizeAlgo Int ())
@@ -189,8 +402,34 @@
  where
  qc prop = quickCheckWith args prop
 
-main = do putStrLn "Int tests:"
+-- | The number of properties that have failed so far.
+failures :: IORef Int
+failures = unsafePerformIO (newIORef 0)
+{-# NOINLINE failures #-}
+
+-- | Like 'QC.quickCheckWith', but records failures so that the test suite
+-- can exit with a failure status.
+quickCheckWith :: Testable prop => Args -> prop -> IO ()
+quickCheckWith a p = do
+  r <- QC.quickCheckWithResult a p
+  unless (isSuccess r) $ modifyIORef' failures (+ 1)
+
+quickCheck :: Testable prop => prop -> IO ()
+quickCheck = quickCheckWith stdArgs
+
+main :: IO ()
+main = do
+  runTests
+  n <- readIORef failures
+  when (n > 0) $ do
+    putStrLn (show n ++ " properties failed")
+    exitFailure
+
+runTests :: IO ()
+runTests = do
+          putStrLn "Int tests:"
           check_Int_sort
+          check_Int_sortUniq
           check_Int_partialsort
           check_Int_select
           putStrLn "Radix sort tests:"
@@ -207,3 +446,19 @@
           check_search_range
           putStrLn "Corner cases:"
           check_corners
+          putStrLn "Algorithms:"
+          check_nub
+          putStrLn "Large structured inputs:"
+          check_large
+          putStrLn "Sub-range (ByBounds) operations:"
+          check_bounds
+          putStrLn "Heap operations:"
+          check_heap_ops
+          putStrLn "Introsort worst-case inputs:"
+          check_killer
+          putStrLn "American flag sort on compound types:"
+          check_flag_compound
+          putStrLn "Searching:"
+          check_search
+          putStrLn "Unboxed, storable and primitive vectors:"
+          check_vector_types
diff --git a/tests/properties/Util.hs b/tests/properties/Util.hs
--- a/tests/properties/Util.hs
+++ b/tests/properties/Util.hs
@@ -7,6 +7,7 @@
 
 import Data.Word
 import Data.Int
+import qualified Data.List as L
 
 import qualified Data.ByteString as B
 
@@ -31,3 +32,137 @@
 instance Arbitrary B.ByteString where
   arbitrary = B.pack `fmap` arbitrary
 
+
+-- | A large vector of 'Int' keys with a particular structure.
+--
+-- The default QuickCheck size limit keeps ordinary 'Arbitrary' vectors under
+-- about 100 elements, which is too small to reach the run merging and
+-- galloping code in Tim sort, the deeper merge levels of merge sort, or the
+-- heap sort fallback in introsort. This generator produces vectors with
+-- thousands of elements, in shapes that commonly expose sorting bugs.
+data LargeVec = LargeVec String (V.Vector Int)
+
+instance Show LargeVec where
+  show (LargeVec shape v) =
+    "LargeVec " ++ shape ++ " (length " ++ show (V.length v) ++ ") " ++ show v
+
+instance Arbitrary LargeVec where
+  arbitrary = do
+    n <- choose (64, 5000)
+    (shape, gen) <- elements largeShapes
+    LargeVec shape . V.fromList <$> gen n
+
+  -- Shrinking does not preserve the shape, but any smaller failing vector is
+  -- still a valid (and more readable) counterexample.
+  shrink (LargeVec shape v)
+    | len < 2   = []
+    | otherwise = [ LargeVec shape (V.take half v)
+                  , LargeVec shape (V.drop half v)
+                  , LargeVec shape (V.take (len - 1) v)
+                  , LargeVec shape (V.drop 1 v)
+                  ]
+   where
+   len  = V.length v
+   half = len `div` 2
+
+largeShapes :: [(String, Int -> Gen [Int])]
+largeShapes =
+  [ ("random",          \n -> vectorOf n (choose (-n, n)))
+  , ("few-distinct",    \n -> vectorOf n (choose (0, 4)))
+  , ("all-equal",       \n -> pure (Prelude.replicate n 7))
+  , ("ascending",       \n -> pure [1 .. n])
+  , ("ascending-dups",  \n -> scanl1 (+) <$> vectorOf n (choose (0, 1)))
+  , ("descending",      \n -> pure [n, n - 1 .. 1])
+  , ("descending-dups", \n -> scanl1 (-) <$> vectorOf n (choose (0, 1)))
+  , ("organ-pipe",      \n -> let h = n `div` 2
+                               in pure ([1 .. h] ++ [n - h, n - h - 1 .. 1]))
+  , ("sawtooth",        \n -> do m <- choose (2, 200)
+                                 pure [ i `mod` m | i <- [0 .. n - 1] ])
+  , ("sorted-runs",     sortedRuns)
+  , ("nearly-sorted",   nearlySorted)
+  , ("sorted-tail",     \n -> do k <- choose (1, 20)
+                                 t <- vectorOf k (choose (-n, n))
+                                 pure ([1 .. n - k] ++ t))
+  ]
+
+-- | Concatenated ascending runs of random lengths. Runs drawn from disjoint
+-- value ranges make Tim sort's galloping mode kick in.
+sortedRuns :: Int -> Gen [Int]
+sortedRuns n = go n
+ where
+ go 0 = pure []
+ go r = do
+   len  <- choose (1, min r 300)
+   base <- choose (-n, n)
+   step <- choose (0, 3)
+   rest <- go (r - len)
+   pure (Prelude.take len [base, base + step ..] ++ rest)
+
+-- | An ascending sequence with a few random elements swapped.
+nearlySorted :: Int -> Gen [Int]
+nearlySorted n = do
+  k     <- choose (1, 10)
+  swaps <- vectorOf k ((,) <$> choose (0, n - 1) <*> choose (0, n - 1))
+  -- Apply the swaps in turn, so the result is a permutation of [1 .. n].
+  pure . V.toList $ V.modify (\mv -> Control.Monad.mapM_ (uncurry (swap mv)) swaps) (V.fromList [1 .. n])
+
+-- | A vector together with a sub-range [l, u) of it and a count k with
+-- 0 <= k <= u - l, for testing the @...ByBounds@ functions. The vector is
+-- either a small arbitrary one or a 'LargeVec'.
+data BoundsCase = BoundsCase (V.Vector Int) Int Int Int
+
+instance Show BoundsCase where
+  show (BoundsCase v l u k) =
+    "BoundsCase (length " ++ show (V.length v) ++ ") l=" ++ show l
+      ++ " u=" ++ show u ++ " k=" ++ show k ++ " " ++ show v
+
+instance Arbitrary BoundsCase where
+  arbitrary = do
+    v <- oneof [ V.fromList <$> listOf (choose (-20, 20))
+               , (\(LargeVec _ lv) -> lv) <$> arbitrary
+               ]
+    let n = V.length v
+    l <- choose (0, n)
+    u <- choose (l, n)
+    k <- choose (0, u - l)
+    pure (BoundsCase v l u k)
+
+  shrink (BoundsCase v l u k) =
+    [ BoundsCase (V.take u v) l u k | u < n ]
+      ++ [ BoundsCase (V.take (u + (n - u) `div` 2) v) l u k | n - u > 1 ]
+      ++ [ BoundsCase (V.drop l v) 0 (u - l) k | l > 0 ]
+      ++ [ BoundsCase (V.drop (l `div` 2) v) (l - l `div` 2) (u - l `div` 2) k | l > 1 ]
+      ++ [ BoundsCase (V.take a v V.++ V.drop b v) l (u - d) (min k (u - l - d))
+         | (a, b) <- cuts, b > a, let d = b - a ]
+      ++ [ BoundsCase v l u (k `div` 2) | k > 0 ]
+   where
+   n    = V.length v
+   half = (u - l) `div` 2
+   -- Remove the upper half, lower half or last element of [l, u). An empty
+   -- range has nothing to cut, and (u - 1, u) would lie outside it.
+   cuts | u > l     = [(l + half, u), (l, l + half), (u - 1, u)]
+        | otherwise = []
+
+-- | A sorted vector together with a sub-range [l, u) of it and a key to
+-- search for, which is either one of the elements in the range or an
+-- arbitrary value.
+data SearchCase = SearchCase (V.Vector Int) Int Int Int
+
+instance Show SearchCase where
+  show (SearchCase v l u e) =
+    "SearchCase (length " ++ show (V.length v) ++ ") l=" ++ show l
+      ++ " u=" ++ show u ++ " e=" ++ show e ++ " " ++ show v
+
+instance Arbitrary SearchCase where
+  arbitrary = do
+    BoundsCase v0 l u _ <- arbitrary
+    let v = V.fromList (L.sort (V.toList v0))
+    e <- if u > l
+           then oneof [ (v V.!) <$> choose (l, u - 1), choose (-50, 50)
+                      , pure (minBound + 1), pure (maxBound - 1) ]
+           else choose (-50, 50)
+    pure (SearchCase v l u e)
+
+  -- Shrinking only removes elements, so the vector stays sorted.
+  shrink (SearchCase v l u e) =
+    [ SearchCase v' l' u' e | BoundsCase v' l' u' _ <- shrink (BoundsCase v l u 0) ]
diff --git a/vector-algorithms.cabal b/vector-algorithms.cabal
--- a/vector-algorithms.cabal
+++ b/vector-algorithms.cabal
@@ -1,5 +1,6 @@
+cabal-version:     >= 1.10
 name:              vector-algorithms
-version:           0.8.0.4
+version:           0.9.1.1
 license:           BSD3
 license-file:      LICENSE
 author:            Dan Doel
@@ -13,9 +14,22 @@
 description:       Efficient algorithms for sorting vector arrays. At some stage
                    other vector algorithms may be added.
 build-type:        Simple
-cabal-version:     >= 1.10
+
 extra-source-files: CHANGELOG.md
 
+tested-with:
+  GHC == 9.14.1
+  GHC == 9.12.2
+  GHC == 9.10.2
+  GHC == 9.8.4
+  GHC == 9.6.7
+  GHC == 9.4.8
+  GHC == 9.2.8
+  GHC == 9.0.2
+  GHC == 8.10.7
+  GHC == 8.8.4
+  GHC == 8.6.5
+  GHC == 8.4.4
 
 flag BoundsChecks
   description: Enable bounds checking
@@ -36,10 +50,6 @@
                performance
   default: True
 
-flag properties
-  description: Enable the quickcheck tests
-  default: True
-
 -- flag dump-simpl
 --   description: Dumps the simplified core during compilation
 --   default: False
@@ -56,15 +66,17 @@
   hs-source-dirs: src
   default-language: Haskell2010
 
-  build-depends: base >= 4.5 && < 5,
-                 vector >= 0.6 && < 0.13,
-                 primitive >=0.3 && <0.8,
-                 bytestring >= 0.9 && < 1.0
+  build-depends: base >= 4.8 && < 5,
+                 bitvec >= 1.0 && < 1.2,
+                 vector >= 0.6 && < 0.14,
+                 primitive >= 0.6.2.0 && < 0.10,
+                 bytestring >= 0.9 && < 1
 
   if ! impl (ghc >= 7.8)
-    build-depends: tagged >= 0.4 && < 0.9
+    build-depends: tagged >= 0.4 && < 0.10
 
   exposed-modules:
+    Data.Vector.Algorithms
     Data.Vector.Algorithms.Optimal
     Data.Vector.Algorithms.Insertion
     Data.Vector.Algorithms.Intro
@@ -81,6 +93,14 @@
   ghc-options:
     -funbox-strict-fields
 
+  -- The same warnings that CI (see .github/workflows/haskell-ci.yml) turns
+  -- into errors.
+  ghc-options: -Wmissing-methods -Wmissing-fields
+  if impl(ghc >= 9.0)
+    ghc-options: -Wincomplete-patterns -Wincomplete-uni-patterns
+  if impl(ghc >= 9.4)
+    ghc-options: -Wunused-packages
+
   -- Cabal/Hackage complains about these
   -- if flag(dump-simpl)
   --   ghc-options: -ddump-simpl -ddump-to-file
@@ -119,6 +139,14 @@
   build-depends: base, mwc-random, vector, vector-algorithms
   ghc-options: -Wall
 
+  -- The same warnings that CI (see .github/workflows/haskell-ci.yml) turns
+  -- into errors.
+  ghc-options: -Wmissing-methods -Wmissing-fields
+  if impl(ghc >= 9.0)
+    ghc-options: -Wincomplete-patterns -Wincomplete-uni-patterns
+  if impl(ghc >= 9.4)
+    ghc-options: -Wunused-packages
+
   -- Cabal/Hackage complains about these
   -- if flag(dump-simpl)
   --   ghc-options: -ddump-simpl -ddump-to-file
@@ -133,21 +161,26 @@
   default-language: Haskell2010
 
   other-modules:
+    Adversary
     Optimal
     Properties
     Util
 
-  if !flag(properties)
-    buildable: False
-  else
-    build-depends:
-      base,
-      bytestring,
-      containers,
-      QuickCheck > 2.9 && < 2.15,
-      vector,
-      vector-algorithms
+  build-depends:
+    base >= 4.9,
+    bytestring,
+    containers,
+    QuickCheck > 2.9 && < 2.20,
+    vector,
+    vector-algorithms
 
+  -- The same warnings that CI (see .github/workflows/haskell-ci.yml) turns
+  -- into errors.
+  ghc-options: -Wmissing-methods -Wmissing-fields
+  if impl(ghc >= 9.0)
+    ghc-options: -Wincomplete-patterns -Wincomplete-uni-patterns
+  if impl(ghc >= 9.4)
+    ghc-options: -Wunused-packages
+
   if flag(llvm)
     ghc-options: -fllvm
-
