Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. (ns binary.core
  2. (:gen-class))
  3. ; wikipedia algorithm for binary search
  4. ; Given an array A of n elements with values or records A0 ... An‚àí1,
  5. ; and target value T
  6. ; Set L to 0 and R to n ‚àí 1.
  7. ; If L > R, the search terminates as unsuccessful.
  8. ; Set m (the position of the middle element) to the floor of (L + R)‚Ää/‚Ää2.
  9. ; If Am < T, set L to m + 1 and go to step 2.
  10. ; If Am > T, set R to m – 1 and go to step 2.
  11. ; Now Am = T, the search is done; return m.
  12.  
  13. (defn binary-search [nums num]
  14. (defn recursor [nums num low-index high-index]
  15. (let [middle-index (int (/ (+ low-index high-index) 2))
  16. test-num (get nums middle-index)]
  17. (cond
  18. ; if test case is bigger than target set low index to current middle + 1
  19. (< test-num num) (recursor nums num (+ middle-index 1) high-index)
  20. ; if test case is lower than target set high-index to current middle index - 1
  21. (> test-num num) (recursor nums num low-index (- middle-index 1))
  22. ; otherwise you have a match
  23. :else middle-index)))
  24. (let [low-index 0
  25. high-index (- (count nums) 1)]
  26. (if (or (> low-index high-index) (< num low-index) (> num high-index))
  27. (throw (Exception. "Search outside of bounds"))
  28. (recursor nums num low-index high-index))))
  29.  
  30. (defn -main
  31. "Naive recursive binary search in clojure"
  32. [& args]
  33. (def nums [0 1 2 3 4 5 6 7 8 9 10])
  34. (println (binary-search nums 10)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement