Binary Search Examples in C#
Returns the zero-based index of the item in the sorted list. If the items is not found, returns a negative number.
This List<T> method works only if the type T implements IComparable<T> or IComparable interface.
Example 1: Simple using
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { var list = new List<int>(); list.Add(100); list.Add(200); list.Add(300); list.Add(400); list.Add(500); list.Add(600); list.Add(700); int index = list.BinarySearch(600); Console.WriteLine(index); Console.ReadLine(); } } |
Output:
1 2 3 |
5 |
Example 2: This BinarySearch method overload uses specified comparer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; using System.Collections.Generic; class Program { public class MyComparer : IComparer<int> { public int Compare(int x, int y) { return x.CompareTo(y); } } static void Main(string[] args) { var list = new List<int>(); list.Add(100); list.Add(200); list.Add(300); list.Add(400); list.Add(500); list.Add(600); list.Add(700); int index = list.BinarySearch( item: 600, comparer: new MyComparer()); Console.WriteLine(index); Console.ReadLine(); } } |
Output:
1 2 3 |
5 |
Example 3: This BinarySearch method overload uses specified comparer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
using System; using System.Collections.Generic; class Person { string name; int age; public Person(string n,int a) { Name = n; Age = age; } public string Name { get => name; set => name = value; } public int Age { get => age; set => age = value; } } class Program { public class PersonComparer : IComparer<Person> { public int Compare(Person x, Person y) { return x.Age.CompareTo(y.Age); } } static void Main(string[] args) { var list = new List<Person>(); list.Add( new Person("Mark",32)); list.Add(new Person("Jack",35)); list.Add(new Person("Linda",30)); list.Add(new Person("Abrahim",42)); list.Add(new Person("Sammy",25)); int index = list.BinarySearch( item: new Person("Linda",30), comparer: new PersonComparer()); Console.WriteLine(index); Console.ReadLine(); } } |
Output:
1 2 3 |
2 |
Example 4: This BinarySearch method overload uses specified comparer and search in specified range.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; using System.Collections.Generic; class Program { public class MyComparer : IComparer<int> { public int Compare(int x, int y) { return x.CompareTo(y); } } static void Main(string[] args) { var list = new List<int>(); list.Add(100); list.Add(200); list.Add(300); list.Add(400); list.Add(500); list.Add(600); list.Add(700); int index = list.BinarySearch( index: 1, count: 4, item: 600, comparer: new MyComparer()); Console.WriteLine(index); Console.ReadLine(); } } |
Output:
1 2 3 |
-6 |