C# | List.BinarySearch(T, Comparer<T> )
Last Updated :
07 Aug, 2024
This method searches for an element in the entire sorted
List using the
specified comparer and returns the zero-based index of the searched element.
Syntax :
public int BinarySearch (T item, IComparer<T> comparer);
Parameters :
Here, the parameters are :
"item" - Which is the item to locate and the value of
item can be
null or
reference type.
"comparer" - When comparing elements then use the
IComparer implementation.
Returns :
If item is found, then this method returns the
zero-based index of the element to be searched for and if not found, then a negative number that is the
bitwise complement of the index of the next element will be return and the complement is larger than that item. If there is no larger element, the
bitwise complement of Count will be return.
Exceptions :
InvalidOperationException
Example :
[sourcecode language="csharp"]
//C# program to demonstrate List.BinarySearch(T, Comparer <T>) method
using System;
using System.Collections.Generic;
class GFG : IComparer<string>
{
public int Compare(string x, string y)
{
if (x == null || y == null)
{
return 0;
}
return x.CompareTo(y);
//"CompareTo()" method
}
}
class geek
{
public static void Main()
{
//list creation
List<string> list1 = new List<string>();
//list elements
list1.Add("B");
list1.Add("C");
list1.Add("E");
list1.Add("A");
//prints Original list
Console.WriteLine("Original string");
foreach(string g in list1)
{
Console.WriteLine(g);
}
GFG gg = new GFG();
list1.Sort(gg);
//sort the list
//prits the sorted form of original list
Console.WriteLine("\nList in sorted form");
foreach (string g in list1)
{
Console.WriteLine(g);
}
int index = list1.BinarySearch("D", gg);
//"D" is going to insert
//"gg" is the IComparer
if (index < 0)
{
list1.Insert(~index, "D");
}
//prints the final List
Console.WriteLine("\nAfetr inserting \"D\" in the List");
foreach (string g in list1)
{
Console.WriteLine(g);
}
}
}
[/sourcecode]
Output :
Original string
B
C
E
A
List in sorted form
A
B
C
E
Afetr inserting "D" in the List
A
B
C
D
E
Example 2 :
In this example, the List is created with some integer values and to insert a new integer using
BinarySearch(T, Comparer <T>)method in the List by using a user define function.
[sourcecode language="csharp"]
//C# program to demonstrate List.BinarySearch(T, Comparer <T>) method
using System;
using System.Collections.Generic;
class GFG : IComparer<int>
{
public int Compare(int x, int y)
{
if (x == 0 || y == 0)
{
return 0;
}
return x.CompareTo(y);
}
}
class geek
{
public static void Main()
{
//list creation
List<int> list1 = new List<int>()
{
5,6,1,9
//list elements
};
//prints Original list
Console.WriteLine("Original string");
foreach(int g in list1)
{
Console.WriteLine(g);
}
GFG gg = new GFG();
//creating object of class GFG
list1.Sort(gg);
//sort the list
//prits the sorted form of original list
Console.WriteLine("\nList in sorted form");
foreach (int g in list1)
{
Console.WriteLine(g);
}
bSearch b = new bSearch();
b.binarySearch(list1);
}
}
class bSearch
{
public void binarySearch(List<int> list1)
{
GFG gg = new GFG();
//creating object of class GFG
int index = list1.BinarySearch(3, gg);
//"3" is going to insert
//"gg" is the IComparer
if (index < 0)
{
list1.Insert(~index, 3);
}
//prints the final List
Console.WriteLine("\nAfter inserting \"3\" in the List");
foreach (int g in list1)
{
Console.WriteLine(g);
}
}
}
[/sourcecode]
Output :
Original string
5
6
1
9
List in sorted form
1
5
6
9
After inserting "3" in the List
1
3
5
6
9
Similar Reads
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
Decorators in Python
In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
What is a Neural Network?
Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns, and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamenta
14 min read
Sliding Window Technique
Sliding Window Technique is a method used to solve problems that involve subarray or substring or window. The main idea is to use the results of previous window to do computations for the next window. This technique is commonly used in algorithms like finding subarrays with a specific sum, finding t
13 min read
Read JSON file using Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Pytho
4 min read
ArrayList in Java
Java ArrayList is a part of the collections framework and it is a class of java.util package. It provides us with dynamic-sized arrays in Java. The main advantage of ArrayList is that, unlike normal arrays, we don't need to mention the size when creating ArrayList. It automatically adjusts its capac
9 min read
Multithreading in Python
This article covers the basics of multithreading in Python programming language. Just like multiprocessing , multithreading is a way of achieving multitasking. In multithreading, the concept of threads is used. Let us first understand the concept of thread in computer architecture. What is a Process
8 min read
Python Match Case Statement
Introduced in Python 3.10, the match case statement offers a powerful mechanism for pattern matching in Python. It allows us to perform more expressive and readable conditional checks. Unlike traditional if-elif-else chains, which can become unwieldy with complex conditions, the match-case statement
7 min read
Two Pointers Technique
Two pointers is really an easy and effective technique that is typically used for Two Sum in Sorted Arrays, Closest Two Sum, Three Sum, Four Sum, Trapping Rain Water and many other popular interview questions. Given a sorted array arr (sorted in ascending order) and a target, find if there exists an
11 min read
Regression in machine learning
Regression in machine learning refers to a supervised learning technique where the goal is to predict a continuous numerical value based on one or more independent features. It finds relationships between variables so that predictions can be made. we have two types of variables present in regression
5 min read