Cubesteak Central

A “Better” Way to Search Arrays in MT4

August 21, 2006 5:00 pm

MT4 provides the function ArrayBSearch to search arrays. It seems a bit “non-standard” to me, in that according to the documentation, it “returns the index of the first occurrence of a value in the first dimension of array if possible, or the nearest one, if the occurrence is not found.”

It wasn’t readily apparent to me what the heck that meant, so I did a little experimenting. I did the following:

double foo[10] = {1,2,3,4,5,6,7,8,9,10};
ArraySort(foo);
int index = ArrayBsearch(foo,4);
Print ("found: "+index);
index = ArrayBsearch(foo,11);
Print ("not found: "+index);

And got:

found: 3
not found: 9

And then did this:

double foo[10] = {1,2,3,4,5,6,7,8,9,10};
ArraySort(foo);
int index = ArrayBsearch(foo,4);
Print ("found: "+index);
index = ArrayBsearch(foo,-1);
Print ("not found: "+index);

And got:

found: 3
not found: 0

So, it seems that this means that ArrayBsearch returns either the first or the last index position if your number isn’t found in the array. To me, that’s kind of dumb, as it means you still have no idea if the first or last index position actually contains the item you are searching for! It could mean it found your value, or it could mean it DIDN’T find your value. Not really the sort of information I’m looking for in a “search” function.

If you do a Google search for “array bsearch”, you’ll find several examples of these kinds of searches. They pretty much boil down to the following:

bsearch returns a pointer to an occurrence of key in the array pointed to by base. If key is not found, the function returns NULL.

So, I created this little function as a more “sane” array search for MT4. Since we don’t have access to pointers, I just used a “-1″ return instead. I hope you like it!

MetaQuotes 4 Language File ArraySearch.mq4
ArraySearch.zip

One Response to “A “Better” Way to Search Arrays in MT4”

[...] Also included in this file, is the single dimension array search function that I posted earlier (see that post for more details) and 2 simple array “printing” functions.  These printing functions output to the “Experts” tab of MT4’s terminal window. [...]

Care to comment?