quicksort in haskell
Here is an implementation of the quicksort algorithm in Haskell:
quicksort :: Ord a => [a] -> [a]
quicksort [] = []
quicksort (x:xs) = quicksort [y | y <- xs, y <= x] ++ [x] ++ quicksort [y | y <- xs, y > x]
This implementation uses a list comprehension to split the input list into two parts: one containing elements less than or equal to the pivot x
, and one containing elements greater than x
. It then recursively applies the quicksort algorithm to these two parts and concatenates the results.
To use the quicksort
function, simply pass a list of elements as an argument. For example:
main :: IO ()
main = do
let unsortedList = [4, 2, 8, 5, 1, 9, 3]
let sortedList = quicksort unsortedList
print sortedList
This will output [1,2,3,4,5,8,9]
, which is the sorted version of the input list [4, 2, 8, 5, 1, 9, 3]
.