Skip to content

Instantly share code, notes, and snippets.

@kuanyui
Created October 5, 2014 14:56
Show Gist options
  • Save kuanyui/96d4bf0b487b5153d4c9 to your computer and use it in GitHub Desktop.
Save kuanyui/96d4bf0b487b5153d4c9 to your computer and use it in GitHub Desktop.
Quicksort algorithm with recursive.
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smallerSorted = quicksort [a | a <- xs, a <= x]
largerSorted = quicksort [a | a <- xs, a > x]
in smallerSorted ++ [x] ++ largerSorted
;; (`mapcar' will return a list with a lot of NIL)
;; With `remove-if-not'
(defun quicksort (list)
(cond ((null list)
'())
(t
(append (quicksort (remove-if-not (lambda (x) (<= x (car list))) (cdr list)))
(list (car list))
(quicksort (remove-if-not (lambda (x) (> x (car list))) (cdr list)))))))
;; Method 2 : without `remove-if-not'
(defun collect (condition list)
"Apply CONDITION function to each element in list. if return non-nil,
collect the element.
e.g. (collect (lambda (x) (> x 5)) '(1 2 6 6 7 3 9)) => (6 6 7 9)"
(cond ((null list)
nil)
((funcall condition (car list))
(append (list (car list)) (collect condition (cdr list))))
(t
(collect condition (cdr list)))))
(defun quicksort (list)
(cond ((null list)
'())
(t
(append (quicksort (collect (lambda (x) (<= x (car list))) (cdr list)))
(list (car list))
(quicksort (collect (lambda (x) (> x (car list))) (cdr list)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment