* Two algorithms: either
- traversing an array or
- duplicating its content in a hash (“associative array” that is?) for a fast lookup;
* Using ‘grep’ or ‘eq’;
* Assuming that arrays look like qw /I am an array, yeah…/.
####
SMALL;
UNSORTED (== no assumptions about distribution of elements);
CONTAIN ONLY SHORT STRINGS
##
##
* Traversing an array should never be used for searching;
* Using a hash is a pretty smart solution, except:
- It has memory implication (hence not always can be used);
- It slows down considerably for huge arrays (or, at least you have to build your own hash structure with some pretty hashing function);
- In any case, questions arise: is it smart to build it every time one needs a lookup? What if the contents of an array change all the time?.., etc.
* There are other algorithms in CS.
##
##
$X = "x";
@array = qw / x y z 1 2 3 /;
return exists {map { $_ => 1 } @array}->{$X};
##
##
- a sub
- that takes two arguments : an array of ints and an int;
- assumes that the array is sorted;
- uses binary search :-);
- returns an index of the element or undef.