Advertisement
Vermiculus

Buggy Quicksort

Oct 20th, 2012
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scheme 1.09 KB | None | 0 0
  1. ;;
  2. ; partition
  3. ; ---------
  4. ; Takes in a list and a pivot value
  5. ; Returns the list split into two parts:
  6. ;     1) All elements <= p (but not including that specific p)
  7. ;     2) All elements > p
  8. (define (partition lst p) (list
  9.                                (append
  10.                                 (filter (lambda (n) (< n p)) lst)
  11.                                 (cdr (filter (lambda (n) (= n p)) lst)))
  12.                                (filter (lambda (n) (> n p)) lst)))
  13.  
  14. ;;
  15. ; quicksort
  16. ; ---------
  17. ; Quicksort implementation
  18. (define (quicksort lst)
  19.   (cond ((null? lst) lst) ; If the list is empty, return
  20.         ((null? (cdr lst)) lst) ; If the list is a singleton, return
  21.         (else (flatten (list ; Otherwise, return a new list, choosing a pivot value of (car lst)
  22.                         (quicksort (car (partition lst (car lst)))) ; with the quick-sorted left side
  23.                         (car lst) ; the pivot value
  24.                         (quicksort (cdr (partition lst (car lst)))) ; and the quick-sorted right side
  25.                         )
  26.               )
  27.         )
  28.   )
  29. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement