I must be in a head block, i'm jsut not getting it at all:
my problem is the negative numbers, there just not coming out how i expect
here is the code:
=================================
Object objitem= itemsWeight;
int myIndex = arrWeightList.BinarySearch(objitem);
if(myIndex < 0)
{
myIndex = (Math.Abs(myIndex) + 1) * -1;
}
==========================================
Array holds: 1, 1.0587, 2, 3, 4,
objitem holds: 1.500
myIndex outputs: -4
objitem holds: 3.500
myIndex outputs: -6
===========================
I'm completely stuck with this and I've searched quite a bit on the net I
can't find anything
Is my code right? I bet it's so blindingly obvious, I just can't see it.
Thanks
Mike
Nicholas Paldino said:
Mike,
I originally posted the formula:
<result> = (<index of next highest value> + 1) * -1
So, if you do this:
abs(<result of call to BinarySearch>) - 1
Applying that, you get 2, which is the index of the value 2.43, which is
the value that comes after the search value of 1.786. At this point, you
could compare it to the element before (at index 1) and determine which
element is closer.
Don't worry about asking for clarification. If it was a bother, I would
have stopped answering you a long time ago =)
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)
mike said:
Thanks Nicholas for your help i know you must be getting fed up of me,
but....
when i have a negative number how can i get the "next" element in the array?
in other words if i have a negative how to i make in into the index of the
next number along?
thanks again !!
message Mike,
It produces a negative number to let you know that there was not an
exact match found in the array. If it gave you a positive number, then
you
would think that it actually found the element you are looking for.
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)
Fantastic,
Sorry to be a pain but could you explain how i find the index of the
closest
match when binarysearch produces a negative number i'm really confused?
Thanks
Mike
in
message Mike,
It seems like your array is sorted. If this is the case, then you
can
call the static BinarySearch method on the Array class to find out.
You would pass your array, along with your number. If the result
is
a
non negative number, then that is the index in the array that it is
found
in. If the number is negative, then that is equal to:
<result> = (<index of next highest value> + 1) * -1
So, in your case, it will return -3.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)
I have ListArray with number in Eg:
1, 1.456, 2.43, 4, 6.78
next i have a decimal variable containing one number EG:
1.786
Could someone please tell me how i find the "closest match" number
below
the
decimal variable from the arraylist.
Thanks ever so much in advance