vbinsearch.scm 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. ;;; The sort package -- binary search -*- Scheme -*-
  2. ;;; Copyright (c) 1998 by Olin Shivers.
  3. ;;; This code is in the public domain.
  4. ;;; Olin Shivers 98/11
  5. ;;; Returns the index of the matching element.
  6. ;;; (vector-binary-search < car 4 '#((1 . one) (3 . three)
  7. ;;; (4 . four) (25 . twenty-five)))
  8. ;;; => 2
  9. (define (vector-binary-search key< elt->key key v . maybe-start+end)
  10. (call-with-values
  11. (lambda () (vector-start+end v maybe-start+end))
  12. (lambda (start end)
  13. (let lp ((left start) (right end)) ; Search V[left,right).
  14. (and (< left right)
  15. (let* ((m (quotient (+ left right) 2))
  16. (elt (vector-ref v m))
  17. (elt-key (elt->key elt)))
  18. (cond ((key< key elt-key) (lp left m))
  19. ((key< elt-key key) (lp (+ m 1) right))
  20. (else m))))))))
  21. (define (vector-binary-search3 compare v . maybe-start+end)
  22. (call-with-values
  23. (lambda () (vector-start+end v maybe-start+end))
  24. (lambda (start end)
  25. (let lp ((left start) (right end)) ; Search V[left,right).
  26. (and (< left right)
  27. (let* ((m (quotient (+ left right) 2))
  28. (sign (compare (vector-ref v m))))
  29. (cond ((> sign 0) (lp left m))
  30. ((< sign 0) (lp (+ m 1) right))
  31. (else m))))))))