Lisp 快排

(defun main-qsort (arr)
  (let ((start 0) (end (- (length arr) 1)))
    (qsort start end arr))
  (print arr)
)

(defun qsort (start end arr)        ;note the variable arr is a list
  (when (< end start)
    (return-from qsort NIL))
  (when (= end start)
    (if (> (elt arr start) (elt arr end)) 
    (rotatef (elt arr start) (elt arr end)))
    (return-from qsort T))
  (when (> end start)
    (let ((mid (partition start end arr)))
      ;(format t "mid=~d  (~d, ~d)" mid start end) (print arr)
      (when (or (< mid start) (> mid end))
    (return-from qsort NIL))
      (when (and (= mid start) (qsort (+ mid 1) end arr))
    (return-from qsort T))
      (when (and (= mid end) (qsort start (- mid 1) arr))
    (return-from qsort T))
      (when (and (> mid start) (< mid end) 
         (qsort start (- mid 1) arr)
         (qsort (+ mid 1) end arr))
    (return-from qsort T))
      ))
)

(defun partition (start end arr)    ;note the variable arr is a list
  (let ((i (- start 1)))
    (do ((j start (1+ j)))
    ((= end j) (1+ i))
      (when (< (elt arr j) (elt arr end))
    (incf i)
    (+ j end)
    (rotatef (elt arr i) (elt arr j))
    ))
    (rotatef (elt arr (1+ i)) (elt arr end))
    ;(print arr)
    (+ (1+ i)))
)


Temp

你可能感兴趣的:(Lisp 快排)