Skip to content

Instantly share code, notes, and snippets.

@wpcarro
Created October 14, 2018 21:32
Show Gist options
  • Select an option

  • Save wpcarro/981844f964f264d930895fb68039f385 to your computer and use it in GitHub Desktop.

Select an option

Save wpcarro/981844f964f264d930895fb68039f385 to your computer and use it in GitHub Desktop.
Naive Haskell implementation of Quick Sort.
--------------------------------------------------------------------------------
import Data.Function ((&))
--------------------------------------------------------------------------------
import qualified Data.List as List
--------------------------------------------------------------------------------
main :: IO ()
main =
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3] & quickSort & show & putStrLn
-- | FP implementation of QuickSort. Intended as an exercise in a high-level
-- understanding of the QuickSort algorithm.
quickSort :: (Ord a) => [a] -> [a]
quickSort [] = []
quickSort [x] = [x]
quickSort xs = quickSort lhs <> [pivot] <> quickSort rhs
where
(pivot, rest) = pivotFor xs
(lhs, _, rhs) = partition pivot rest
-- | Note: partitioning does not happen in-place as it should canonically
partition :: (Ord a) => a -> [a] -> ([a], a, [a])
partition pivot xs = (lhs, pivot, rhs)
where
(lhs, rhs) = List.partition (< pivot) xs
-- | Naive pivot function that just selects the leftmost element as the pivot
pivotFor :: [a] -> (a, [a])
pivotFor (x:rest) = (x, rest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment