Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ;;
- ; partition
- ; ---------
- ; Takes in a list and a pivot value
- ; Returns the list split into two parts:
- ; 1) All elements <= p (but not including that specific p)
- ; 2) All elements > p
- (define (partition lst p) (list
- (append
- (filter (lambda (n) (< n p)) lst)
- (cdr (filter (lambda (n) (= n p)) lst)))
- (filter (lambda (n) (> n p)) lst)))
- ;;
- ; quicksort
- ; ---------
- ; Quicksort implementation
- (define (quicksort lst)
- (cond ((null? lst) lst) ; If the list is empty, return
- ((null? (cdr lst)) lst) ; If the list is a singleton, return
- (else (flatten (list ; Otherwise, return a new list, choosing a pivot value of (car lst)
- (quicksort (car (partition lst (car lst)))) ; with the quick-sorted left side
- (car lst) ; the pivot value
- (quicksort (cdr (partition lst (car lst)))) ; and the quick-sorted right side
- )
- )
- )
- )
- )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement