-- ----------------------------------------------------------------------------- |-- Module : Data.Vector.Algorithms.Insertion-- Copyright : (c) 2008-2010 Dan Doel-- Maintainer : Dan Doel-- Stability : Experimental-- Portability : Portable---- A simple insertion sort. Though it's O(n^2), its iterative nature can be-- beneficial for small arrays. It is used to sort small segments of an array-- by some of the more heavy-duty, recursive algorithms.moduleData.Vector.Algorithms.Insertion(sort,sortBy,sortByBounds,sortByBounds',Comparison)whereimportPreludehiding(read,length)importControl.Monad.PrimitiveimportData.Vector.Generic.MutableimportData.Vector.Algorithms.Common(Comparison)importqualifiedData.Vector.Algorithms.OptimalasO-- | Sorts an entire array using the default comparison for the typesort::(PrimMonadm,MVectorve,Orde)=>v(PrimStatem)e->m()sort=sortBycompare{-# INLINABLE sort #-}-- | Sorts an entire array using a given comparisonsortBy::(PrimMonadm,MVectorve)=>Comparisone->v(PrimStatem)e->m()sortBycmpa=sortByBoundscmpa0(lengtha){-# INLINE sortBy #-}-- | Sorts the portion of an array delimited by [l,u)sortByBounds::(PrimMonadm,MVectorve)=>Comparisone->v(PrimStatem)e->Int->Int->m()sortByBoundscmpalu|len<2=return()|len==2=O.sort2ByOffsetcmpal|len==3=O.sort3ByOffsetcmpal|len==4=O.sort4ByOffsetcmpal|otherwise=O.sort4ByOffsetcmpal>>sortByBounds'cmpal(l+4)uwherelen=u-l{-# INLINE sortByBounds #-}-- | Sorts the portion of the array delimited by [l,u) under the assumption-- that [l,m) is already sorted.sortByBounds'::(PrimMonadm,MVectorve)=>Comparisone->v(PrimStatem)e->Int->Int->Int->m()sortByBounds'cmpalmu=sortmwheresorti|i<u=dov<-unsafeReadaiinsertcmpalvisort(i+1)|otherwise=return(){-# INLINE sortByBounds' #-}-- Given a sorted array in [l,u), inserts val into its proper position,-- yielding a sorted [l,u]insert::(PrimMonadm,MVectorve)=>Comparisone->v(PrimStatem)e->Int->e->Int->m()insertcmpal=loopwhereloopvalj|j<=l=unsafeWritealval|otherwise=doe<-unsafeReada(j-1)casecmpvaleofLT->unsafeWriteaje>>loopval(j-1)_->unsafeWriteajval{-# INLINE insert #-}