BinarySearch() method in C#


BinarySearch() works on a sorted list whether its numeric, alphanumeric or strings. It finds you the index of an element.

Let’s say the following is our list.

List<int> list = new List<int>();
list.Add(70);
list.Add(150);
list.Add(220);
list.Add(250);
list.Add(300);

Now to check the index where 250 is placed, use BinarySearch() method.

list.BinarySearch(250);

Example

 Live Demo

using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      List<int> list = new List<int>();
      list.Add(70);
      list.Add(150);
      list.Add(220);
      list.Add(250);
      list.Add(300);
      int value = list.BinarySearch(250);
      Console.WriteLine("Element 250 at Index: "+value);
   }
}

Output

Element 250 at Index: 3

Updated on: 23-Jun-2020

315 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements