Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about BinarySearch in array

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);
        }
    }
}
like image 234
user2936672 Avatar asked Dec 01 '22 20:12

user2936672


2 Answers

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"

like image 173
nvoigt Avatar answered Dec 10 '22 02:12

nvoigt


As the documentation clearly states, BinarySearch() only makes any sense if the array is sorted:

array must be sorted before calling this method.

like image 37
SLaks Avatar answered Dec 10 '22 03:12

SLaks