Confused about BinarySearch in an array

I am a bit confused about BinarySearch because in many cases this does not work. The program below dispays is -5 and -1. But it should display 1 and 3 in the morning, 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);
        }
    }
}
+4
source share
5 answers

For BinarySearch to work, the array must be sorted . You do not, so it does not work correctly.

Quote: β€œLooks for the entire one-dimensional sorted array for a specific element”

+10
source

As the documentation says , BinarySearch()it only makes sense when sorting an array:

the array must be sorted before calling this method.

+6
source
+2

:

., System.IComparable, System.Array .

, BinarySearch .

+1

, , , Array.Sort() int []. :

static void Main(string[] args)
    {
        int[] array = { 12, 45, 23, 3, 67, 43 };
        Array.Sort(array);
        int index1 = Array.BinarySearch<int>(array, 45);
        int index2 = Array.BinarySearch<int>(array, 3);
        Console.WriteLine(index1);
        Console.WriteLine(index2);
    }
0

All Articles