Re: binary search

Liste des GroupesRevenir à cl lisp 
Sujet : Re: binary search
De : Nobody447095 (at) *nospam* here-nor-there.org (B. Pym)
Groupes : comp.lang.lisp
Date : 30. Jun 2025, 03:20:56
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <103ssa7$1ukpp$1@dont-email.me>
User-Agent : XanaNews/1.18.1.6
Tayssir John Gabbour wrote:

Incidentally, instead of -1, you'll want to return NIL upon failure.
 
Here's a version using LOOP:
 
(defun binary-search (vector item)
  (loop with low       = 0
        with high      = (1- (length vector))
        for middle     = (truncate (+ low high) 2)
        for middle-obj = (aref vector middle)
        do (format t "~&{~S, ~S}, ~S" low high middle) ;debugging
        while (<= low high)
        if      (< middle-obj item) do (setf low  (1+ middle))
        else if (> middle-obj item) do (setf high (1- middle))
        else                        do (return middle)
        finally (return nil)))

Gauche Scheme

(use srfi-43) ; vector operations

(define vec #(0 2 4 5 8 9 20 22 23 26 27 30))

(vector-binary-search vec 22 -)
  ===>
7

Date Sujet#  Auteur
30 Jun 25 o Re: binary search1B. Pym

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal