Created
October 5, 2014 14:56
-
-
Save kuanyui/96d4bf0b487b5153d4c9 to your computer and use it in GitHub Desktop.
Quicksort algorithm with recursive.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; (`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