I am a little bit confused about BinarySearch because in a lot of cases it doesn't work. The program below dispays -5 and -1. But it should display 1 and 3 am I right?
using System;
namespace Binary
{
class Program
{
static void Main()
{
int[] array = { 12, 45, 23, 3, 67, 43 };
int index1 = Array.BinarySearch<int>(array, 45);
int index2 = Array.BinarySearch<int>(array, 3);
Console.WriteLine(index1);
Console.WriteLine(index2);
}
}
}
For a BinarySearch to work, the array needs to be sorted. Yours is not, so it does not work correctly.
Quote: "Searches an entire one-dimensional sorted array for a specific element"
As the documentation clearly states, BinarySearch()
only makes any sense if the array is sorted:
array must be sorted before calling this method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With