Advertisement
Guest User

Untitled

a guest
Dec 19th, 2014
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. (defn- swap [source idx0 idx1]
  2. (def tmp (aget source idx0))
  3. (aset source idx0 (aget source idx1))
  4. (aset source idx1 tmp))
  5.  
  6. ; find median among start/mid/end
  7. (defn- get-pivot [source start len]
  8. (let [end (+ start (dec len)) mid (+ start (int (/ len 2)))]
  9. (if
  10. (or
  11. (and
  12. (> (aget source start) (aget source mid))
  13. (< (aget source start) (aget source end)))
  14. (and
  15. (> (aget source start) (aget source end))
  16. (< (aget source start) (aget source mid))))
  17. start
  18. ; else if
  19. (if
  20. (or
  21. (and
  22. (> (aget source mid) (aget source start))
  23. (< (aget source mid) (aget source end)))
  24. (and
  25. (> (aget source mid) (aget source end))
  26. (< (aget source mid) (aget source start))))
  27. mid
  28. ; else
  29. end))))
  30.  
  31. (defn- get-left-idx [source start pivot]
  32. (loop [idx start]
  33. (if (and (< (aget source idx) (aget source pivot)) (not= pivot idx)) (recur (inc idx)) idx)))
  34.  
  35. (defn- get-right-idx [source start pivot]
  36. (loop [idx start]
  37. (if (and (> (aget source idx) (aget source pivot)) (not= pivot idx)) (recur (dec idx)) idx)))
  38.  
  39. (defn- comp-and-swap [source start len]
  40. (loop [leftIdx start rightIdx (+ start (dec len)) pivot (get-pivot source start len)]
  41. (let [compLeftIdx (get-left-idx source leftIdx, pivot) compRightIdx (get-right-idx source rightIdx pivot)]
  42. (if (and (= compLeftIdx pivot) (not= compRightIdx pivot))
  43. (do
  44. (swap source pivot (inc pivot))
  45. (if (> (- compRightIdx pivot) 1) (swap source pivot compRightIdx))
  46. (recur (inc pivot) compRightIdx (inc pivot)))
  47. ; else if
  48. (if (and (= compRightIdx pivot) (not= compLeftIdx pivot))
  49. (do
  50. (swap source pivot (dec pivot))
  51. (if (> (- pivot compLeftIdx) 1) (swap source pivot compLeftIdx))
  52. (recur compLeftIdx (dec pivot) (dec pivot)))
  53. ; else if
  54. (if (not= compLeftIdx compRightIdx)
  55. (do
  56. (swap source compLeftIdx compRightIdx)
  57. (recur (inc compLeftIdx) (dec compRightIdx) pivot))
  58. ; else
  59. compLeftIdx))))))
  60.  
  61. (defn- do-sort [source start len]
  62. (let [mid (+ (comp-and-swap source start len) 1)]
  63. (if (> len 2)
  64. (do
  65. (do-sort source start (- mid start))
  66. (do-sort source mid (- (+ start len) mid))))))
  67.  
  68. (defn quicksort [source]
  69. (do-sort source 0 (alength source)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement