Page 1 of 1

Nice Simple Binary Search code - very optimised, very quick

Posted: Fri Oct 08, 2004 4:47 pm
by naw
Code updated For 5.20+

Code: Select all

;
; Phil Robinsons JavaScript BinSearch
; Converted to PB by NAW
;

Procedure BinSearch(LENGTH,SRCH4NUM)
;
; Create Data Bit
;
  Dim MYDATA.s(LENGTH+1,3)
  For x = 1 To LENGTH Step 1
    MYDATA(x,0)=Str(x)
    MYDATA(x,1)=Str(Random(100))
    MYDATA(x,2)=Chr(Random(26)+96)
  Next
  Debug("Items  = "+Str(LENGTH))
  Debug("Search = "+Str(SRCH4NUM))
Debug("SearchData="+MYDATA(SRCH4NUM,0)+","+MYDATA(SRCH4NUM,1)+","+MYDATA(SRCH4NUM,2));

;
; Search Bit
;
_low    = 1
_high   = LENGTH+1
_probe  = 0
_target = SRCH4NUM
_ctr    = 0
While (_high - _low ) >1
 _probe = (_high + _low)>>1
   If (Val(MYDATA(_probe,0)) > _target): _high = _probe
      Else: _low = _probe: _ctr + 1
   EndIf
   If (_low = -1 Or Val(MYDATA(_low,0)) <> _target):
   Debug("Missed="+MYDATA(_low,1)+","+MYDATA(_low,2)+","+MYDATA(_low,3))
      Else: Debug("Found="+MYDATA(_low,0)+","+MYDATA(_low,1)+","+MYDATA(_low,2)): ProcedureReturn _ctr
   EndIf
 Wend
EndProcedure

LENGTH   = 1000
SRCH4NUM = Random(LENGTH)+1

TRYS=BinSearch(LENGTH,SRCH4NUM)

Debug("")
Debug(Str(TRYS)+" trys")