Multithreaded Quicksort
;;; Multithreaded Quicksort
(defun swap (a i j)
"swap two elements in an indexable sequence"
(let ((tmp (get a i)))
(put! a i (get a j))
(put! a j tmp)))
(defun random-list (size maxr)
"make list of length size of random number from 0 upto maxr"
(map (lambda (x) (random maxr))
(range 0 size)))
(defun partition (a lo hi)
"partition part of an indexable sequence a"
(let ((pivot (get a hi))
(i lo)
(j lo))
(while (< j hi)
(when (< (get a j) pivot)
(swap a i j)
(setv i (+ i 1)))
(setv j (+ j 1)))
(swap a i hi)
i))
(defun quick-sort (a &OPTIONAL (lo 0) (hi (- (LENGTH a) 1)))
(when (< lo hi)
(let ((p (partition a lo hi))
(t1 (new-thread
(lambda () (quick-sort a lo (- p 1)))))
(t2 (new-thread
(lambda () (quick-sort a (+ p 1) hi)))))
(. t1 "start()")
(. t2 "start()")
(. t1 "join()")
(. t2 "join()")))
a)
(let ((data (random-list 32 100)))
(println "Quick sort in: " data)
(quick-sort data)
(println "Quick sort out: " data))
Output:
Quick sort in: [52, 51, 11, 25, 50, 70, 51, 11, 55, 30, 60, 10, 70, 63, 93, 43, 68, 30, 8, 71, 4, 23, 48, 93, 25, 24, 6, 75, 45, 28, 60, 61]
Quick sort out: [4, 6, 8, 10, 11, 11, 23, 24, 25, 25, 28, 30, 30, 43, 45, 48, 50, 51, 51, 52, 55, 60, 60, 61, 63, 68, 70, 70, 71, 75, 93, 93]