Today I've wrapped my head around binary search. I've heard this is the fastest method of finding indexes in big arrays. So I've decided to write code to see if I'll get an exception in case there was no index which I'm searching for.
int[] longArray = new int[1000];
Random rnd = new Random();
for (int i = 0; i < longArray.Length; i++)
{
longArray[i] = rnd.Next(1, 1000);
}
Array.Sort(longArray);
int indexOfMyNum = Array.BinarySearch(longArray, 706);
Console.WriteLine("Here it is: " + indexOfMyNum);
Now the fun part, there was no exception, my program always returns number which is from time to time a negative one. I know that random wasn't necessary to see this behavior but I wanted to test it on the bigger array. Now my question is, why m'I getting negative index instead of an exception. Correct me if I'm wrong since indexes of an array are directly related to the memory addresses, does it mean that BinarySearch is looking on pieces of memory he shouldn't be allowed to, to see if my number is there?
Does anybody know why it happens instead of an exception?