Tuesday, January 15, 2013

Haskell DSA: Quick Sort

Haskell continues to astound me! I have never implemented the quicksort as simply and, frankly, elegantly as this:

quickSort :: (Ord a) => [a] -> [a]

quickSort [] = []
quickSort (x:xs) = quickSort lesser ++ [x] ++ quickSort greater
 where lesser = [e | e <- xs, e < x]
       greater = [e | e <- xs, e >= x]


Here's a quick, line-by-line for anyone who's interested.
  • quickSort :: (Ord a) => [a] -> [a]
    The optional (gotta love that word in programming) function definition. It basically says that quickSort is a function that takes a list of objects, [a] and returns another list of a. Ord a means that a is ordinal, or, as far as we're concerned, sortable
  • quickSort [] = []
    The first pattern we're trying to match -- if we're given an empty list, return an empty list!
  • quickSort (x:xs) = quickSort lesser ++ [x] ++ quickSort greater
    This line does a few cool things: (1) split up a passed list into a first element and remainder, then (2) return the lower ordered elements and the higher sorted on either sides of the first element!
  • where less = [e | e <- xs, e < x]
          greater = [e | e <- xs, e >= x]

    This where clause uses list comprehensions to build and define the lists of lower and higher ordered values. Note that the higher values are also (if the case may be) equal to the head of the list (also know as the pivot).

No comments:

Post a Comment