Click or drag to resize

AScanBin Function

Scan a sorted array until a value is found or a code block returns 0.

Namespace:  XSharp.RT
Assembly:  XSharp.RT (in XSharp.RT.dll) Version: 2.08
Syntax
 FUNCTION AScanBin(
	aTarget AS ARRAY,
	uSearch AS USUAL
) AS DWORD
View Source

Parameters

aTarget
Type: Array
The sorted array to scan.
uSearch
Type: Usual
The value to scan for.  Unless this argument is a code block, it must match the data type of the elements in <aTarget>.  If <uSearch> is a code block, it should return a numeric value that indicates the outcome of the comparison: a positive value indicates that <uSearch> is greater than the current array element, a 0 stands for equality, and a negative value indicates that <uSearch> is less than the current array element.

Return Value

Type: UInt32
If <uSearch> is a code block, AScanBin() returns the position of the element if the code block returned a value of zero.  Otherwise, AScanBin() returns the position of a matching element.  If multiple occurrences of the same element exist, the returned match is not necessarily the lowest numbered element since AScanBin() uses a binary search algorithm.  AScanBin() returns 0 if no match is found.
Remarks
AScanBin() scans an array for a specified value. If <uSearch> is a code block, AScanBin() scans <aTarget>, by using a binary search algorithm and executes the code block for each element accessed.  As each element is encountered, AScanBin() passes the element's value as an argument to the code block, then performs an Eval() on the code block.  The scanning operation stops when the code block returns a value of zero or when the range of elements to scan is exhausted. Note:  Values are compared using the = operator.  For exact matching (that is, using the == operator), use AScanBinExact().
Examples
This example demonstrates scanning a 3-element array, using both a string and a code block as search criteria.  The code block criteria shows how to perform a case-insensitive search:
X#
aArray := {"Tom", "Mary", "Sue"}
ASort(aArray)
? AScanBin(aArray, "Mary")                                // 1
? AScanBin(aArray, "mary")                                // 0
? AScanBin(aArray, ;
                {|x| MyCompare(x, "MARY")})                // 1
FUNCTION MyCompare(cElement, cSearch) AS SHORTINT
        LOCAL siRet := 0 AS SHORTINT
        cElement := Upper(cElement)
        IF cSearch > cElement
                siRet := 1
        ELSEIF cSearch < cElement
                siRet := -1
                // ELSE defaults to the initial value of 0
        ENDIF
        RETURN siRet
See Also