ArrayList.BinarySearch

  • Thread starter Thread starter Pete Z
  • Start date Start date
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
 
Pete:

Stupid question but is this the actual example....ie is the list definitely
sorted? If not, binary search does give some weird results...
 
Hi William,
Does the ArrayList need to be sorted for BinarySearch to work?
Is that the message I'm getting?

Regards
Pete
 
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.
 
Thanks guys!
Yes, it quite clearly states it on the first line of the documentation.
Regards
Pete
 
Back
Top