home *** CD-ROM | disk | FTP | other *** search
/ CD-ROM Magazine 28 Bonus / CDRomMagazine-SoftKey-ArtPassion-FrenchVersion-Win31Mac.bin / data / shared.dir / 03056_Script_BinarySearch < prev    next >
Text File  |  1996-06-21  |  1KB  |  44 lines

  1. on BinSearchFirstItemInLine source, target
  2.   -- Source must be sorted, and have a blank line at the end.
  3.   
  4.   if (length(source) = 0) or (length(target) = 0) then return 0
  5.   
  6.   set RangeBegin = 1
  7.   set RangeEnd = the number of lines of source
  8.   set CurrentLine = RangeBegin + integer ((RangeEnd - RangeBegin) / 2)
  9.   
  10.   set loopCount = 0 -- For error handling, to avoid infinite loop
  11.   
  12.   set found = FALSE
  13.   
  14.   repeat while found = FALSE
  15.     set maybeTarget = item 1 of line CurrentLine of Source
  16.     -- in case the line begins with a ":"
  17.     if maybeTarget = EMPTY then
  18.       set currentline = currentline - 1
  19.     else if maybeTarget = Target then
  20.       set found = TRUE
  21.     else if maybeTarget < Target then
  22.       set RangeBegin = CurrentLine
  23.       set CurrentLine = RangeBegin + integer ((RangeEnd - RangeBegin) / 2)
  24.     else -- maybeTarget > Target
  25.       set RangeEnd = CurrentLine
  26.       set CurrentLine = RangeBegin + integer ((RangeEnd - RangeBegin) / 2)
  27.     end if
  28.     
  29.     -------------------------------------------------------------------------
  30.     -- Error Handling. If data is not found, avoid an infinite loop.
  31.     
  32.     if abs(RangeEnd - RangeBegin) < 2 then set loopCount = loopCount + 1
  33.     if loopCount > 3 then
  34.       exit repeat
  35.     end if
  36.     
  37.     -------------------------------------------------------------------------
  38.     
  39.   end repeat
  40.   
  41.   if found then return CurrentLine
  42.   else return 0
  43.   
  44. end