Clib Search Array Method
The Clib Search Array method searches an array for a value that you specify. It returns one of the following values:
If it finds the value you specify in the key argument, then it returns an array variable that matches the value you specify in the key argument.
If it does not find the value you specify in the key argument, then it returns the following value:
Null
It only searches through array elements that include a positive index. It ignores array elements that include a negative index.
Format
Clib.bsearch(key, arrayToSort, [elementCount,] compareFunction)
The following table describes the arguments for the Clib Search Array method.
Argument | Description |
---|---|
key |
The value for which this method searches. |
arrayToSort |
The name of the array that this method searches. |
elementCount |
The number of array elements that this method searches. If you do not specify the elementCount argument, then it searches the entire array. |
compareFunction |
A custom function that can affect the sort order. The value for the compareFunction argument must include the following items:
|
Example
The following example uses Clib.qsort and Clib.bsearch to locate a name and related item in a list:
(general) (ListCompareFunction)
function ListCompareFunction(Item1, Item2)
{
return Clib.strcmpi(Item1[0], Item2[0]);
}
(general) (DoListSearch)
function DoListSearch()
// create array of names and favorite food
var list =
{
{“Brent”, “salad”},
{"Laura", "cheese" },
{ "Alby", "sugar" },
{ "Jonathan","pad thai" },
{ "Zaza", "grapefruit" },
{ "Jordan", "pizza" }
};
// sort the list
Clib.qsort(list, ListCompareFunction);
var Key = "brent";
// search for the name Brent in the list
var Found = Clib.bsearch(Key, list, ListCompareFunction);
// display name, or not found
if ( Found != null )
TheApplication().RaiseErrorText(Clib.rsprintf
("%s's favorite food is %s\n", Found[0][0],Found[0][1]));
else
TheApplication().RaiseErrorText("Can not find name in list.");
}