bsearch

bsearch — searches an array or list for a element.

Syntax

bsearch (list_or_array, key, compare_function)

		

Arguments

list_or_array

A list or array whose elements are sorted.

key

The list or array element to search for.

compare_function

A function used to compare the key with the array elements.

Returns

An association list composed of the key and it's position in the array.

Description

This function performs a binary search on an array based on a comparison function you provide. The compare_function must return a negative number if the value is ordinally less than the list or array element, 0 if the two are equal and a positive number if the value is ordinally greater than the list or array element. The array or list must be sorted in an order recognizable by the compare_function for this function to work.

Example

Gamma> function comp (x,y) {x - y;}
(defun comp (x y) (- x y))
Gamma> Ax = array(9,2,11,31,13,8,15,95,17,5,19,6,21);
[9 2 11 31 13 8 15 95 17 5 19 6 21]
Gamma> Sx = sort(Ax,comp);
[2 5 6 8 9 11 13 15 17 19 21 31 95]
Gamma> bsearch(Sx,19,comp);
(19 . 9)
Gamma> bsearch(Sx,5,comp);
(5 . 1)
Gamma> 
		

See Also

sort