ArrayList.BinarySearch

P

Pete Z

Does anyone know why this snippet of code continues to return x with a value
of -1?
Is there an issue with ArrayList.BinarySearch?

ArrayList myAL = new ArrayList();

myAL .Add(1);

myAL .Add(2);

myAL .Add(3);

object oX;

oX = 3;

int x = myAL .BinarySearch(oX)



According to the documentation, x should = 2. Being the index of where the
value 3 exists in myAl.



Regards

Pete
 
W

William Ryan

Pete:

Stupid question but is this the actual example....ie is the list definitely
sorted? If not, binary search does give some weird results...
 
P

Pete Z

Hi William,
Does the ArrayList need to be sorted for BinarySearch to work?
Is that the message I'm getting?

Regards
Pete
 
J

Jon Skeet [C# MVP]

Does the ArrayList need to be sorted for BinarySearch to work?
Is that the message I'm getting?

It's the message from the documentation :)

<quote>
Uses a binary search algorithm to locate a specific element in the
sorted ArrayList or a portion of it.
</quote>

If the list weren't sorted to start with, there's no way a binary
search would work, if you think about how a binary search works.
 
P

Pete Z

Thanks guys!
Yes, it quite clearly states it on the first line of the documentation.
Regards
Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top