FUNCTION BArraySearch > >LPARAMETERS tarray, tsearchfor, tlsoftsearch > >LOCAL lnfirst, lnlast, lnmid, llfound, lnresult >lnfirst = 1 >lnlast = ALEN(tarray, 1) >llfound = .F. >lnresult = 0 >DO WHILE NOT llfound AND lnfirst < lnlast > lnmid = INT(lnfirst + lnlast) > llfound = (tsearchfor = tarray[lnmid]) > IF NOT llfound THEN > IF tsearchfor > tarray[lnmid] THEN > lnfirst = lnmid + 1 > ELSE > lnlast = lnmid - 1 > ENDIF > ENDIF >ENDDO >IF llfound THEN > lnresult = lnmid >ELSE > IF llsoftsearch THEN > lnresult = lnlast > ENDIF >ENDIF >RETURN lnresultThe beauty of this is that it can be implemented, not only with a array, but an ordered list or cursor.
******************************************************************** Function fSearch( aToSearch, cLookForItem, lFindNearest ) As Integer ******************************************************************** Local iHalfLength, iItemToTest, iLastLoops As Integer iHalfLength = Int( ALen( aToSearch ) / 2 ) iItemToTest = iHalfLength iLastLoops = 0 Do While cLookForItem # aToSearch[ iItemToTest ] ; And iLastLoops < 3 iHalfLength = Int( iHalfLength / 2 ) If iHalfLength = 0 Then iLastLoops = iLastLoops + 1 iHalfLength = 1 Endif If cLookForItem < aToSearch[ iItemToTest ] Then iItemToTest = iItemToTest - iHalfLength Else iItemToTest = iItemToTest + iHalfLength Endif EndDo Return Iif( Not lFindNearest And cLookForItem # aToSearch[ iItemToTest ] ; , -1 ; , iItemToTest ) EndFunc