udfArrayItemLocate
int udfArrayItemLocate (arr, any)
;------------------------------------------------------------------------------------------------------------------------------------------
#DefineFunction udfArrayItemLocate (arrArray, anyItem)
If VarType (arrArray) != 256 Then Return -1 ; No array.
If ArrInfo (arrArray, 6) == 0 Then Return -1 ; No elements.
If ArrInfo (arrArray, 0) > 1 Then Return -1 ; Too much dimensions.
intTop = Max (0, ArrInfo (arrArray, 1) - 1)
intBot = 0
While (intTop - intBot - 1)
   intMid = (intTop + intBot) / 2
   If anyItem > arrArray [intMid] Then intBot = intMid
      Else intTop = intMid
EndWhile
If arrArray [intTop] == anyItem Then Return intTop
If arrArray [intBot] == anyItem Then Return intBot
Return -1
;..........................................................................................................................................
; This UDF "udfArrayItemLocate" uses the binary search algorithm
; to locate a given item in a given ascending sorted array.
; The function returns the index number of the found element,
; or returns -1 if the item was not found or the given array does not fit.
;
; The algorithm needs an ascending sorted array.
;
; Detlev Dalitz.20020821.20090507.
;..........................................................................................................................................
#EndFunction
;------------------------------------------------------------------------------------------------------------------------------------------


; Test.

anyItem1 = "ZZZ"
anyItem2 = "???"
anyItem3 = ""
anyItem4 = "zzzz"
anyItem5 = "drei"
anyItem6 = "zero"
anyItem7 = "four"
anyItem8 = "six"

; arrArray contains 21 elements, sorted ascending.
arrArray = Arrayize (",acht,drei,eight,eins,five,four,fuenf,neun,nine,one,sechs,seven,sieben,six,three,two,vier,zero,zwei,zzzz", ",")

intResult1 = udfArrayItemLocate (arrArray, anyItem1) ; -1 ; anyItem is not in array, beyond right edge.
intResult2 = udfArrayItemLocate (arrArray, anyItem2) ; -1 ; anyItem is not in array, beyond left edge.
intResult3 = udfArrayItemLocate (arrArray, anyItem3) ;  0 ; anyItem is in array, left edge.
intResult4 = udfArrayItemLocate (arrArray, anyItem4) ; 20 ; anyItem is in array, right edge.
intResult5 = udfArrayItemLocate (arrArray, anyItem5) ;  2 ; anyItem is in array, element 8 from the middle to the left.
intResult6 = udfArrayItemLocate (arrArray, anyItem6) ; 18 ; anyItem is in array, element 8 from the middle to the right.
intResult7 = udfArrayItemLocate (arrArray, anyItem7) ;  6 ; anyItem is in array, element 4 from the middle to the left.
intResult8 = udfArrayItemLocate (arrArray, anyItem8) ; 14 ; anyItem is in array, element 4 from the middle to the right.

Exit