当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C# List BinarySearch()用法及代码示例


List <T> .BinarySearch()方法使用二进制搜索算法在已排序的List <T>或其一部分中定位特定元素。此方法的重载列表中有3种方法,如下所示:

    • BinarySearch(T)
    • BinarySearch(T,IComparer <T>)
    • BinarySearch(Int32,Int32,T,IComparer <T>)

BinarySearch(T)方法

此方法使用默认比较器在整个排序后的List <T>中搜索元素,并返回搜索到的元素的从零开始的索引。


用法:

public int BinarySearch (T item);

这里,item是要定位的对象,item的值可以为null或引用类型。

返回类型:如果找到该项目,则此方法返回要搜索的元素的从零开始的索引,如果找不到,则将返回一个负数,该负数是下一个元素的索引的按位补码,并且补码为比那个项目大。如果没有更大的元素,则将返回Count的按位补码。

异常:如果默认比较器Default无法找到类型T的IComparable <T>通用接口或IComparable接口的实现,则此方法将提供InvalidOperationException。

以下示例程序旨在说明上述方法的使用:

范例1:

// C# program to illustrate the  
// List<T>.BinarySearch(T) Method 
using System; 
using System.Collections.Generic; 
  
class GFG { 
      
    // Main Method 
    public static void Main() 
    { 
        // List creation 
        List<string> Geek = new List<string>(); 
  
        // List elements 
        Geek.Add("ABCD"); 
        Geek.Add("QRST"); 
        Geek.Add("XYZ"); 
        Geek.Add("IJKL"); 
  
  
        Console.WriteLine("The Original List is:"); 
        foreach(string g in Geek) 
        { 
              
            // prints original List 
            Console.WriteLine(g); 
              
        } 
  
        Console.WriteLine("\nThe List in Sorted form"); 
          
        // sort the List 
        Geek.Sort(); 
      
  
        Console.WriteLine(); 
        foreach(string g in Geek) 
        { 
            // prints the sorted List 
            Console.WriteLine(g); 
              
        } 
  
        Console.WriteLine("\nInsert EFGH:"); 
          
        // insert "EFGH" in the List 
        //"EFGH" insert into its original  
        // position when the List is sorted 
        int index = Geek.BinarySearch("EFGH"); 
          
  
        if (index < 0)  
        { 
              
            Geek.Insert(~index, "EFGH"); 
        } 
  
        Console.WriteLine(); 
          
        foreach(string g in Geek) 
        { 
              
            // prints the sorted list 
            // after inserting "EFGH" 
            Console.WriteLine(g); 
        } 
    } 
}
输出:
The Original List is:
ABCD
QRST
XYZ
IJKL

The List in Sorted form

ABCD
IJKL
QRST
XYZ

Insert EFGH:

ABCD
EFGH
IJKL
QRST
XYZ

范例2:在此示例中,使用一些整数值创建列表,并使用用户定义函数使用BinarySearch(T)方法在列表中插入新的整数。

// C# program to illustrate the  
// List<T>.BinarySearch(T) Method 
using System; 
using System.Collections.Generic; 
  
class GFG { 
      
// method for inserting "3" 
public void binarySearch(List<int> Geek) 
{ 
      
    // insert "3" in the List 
    Console.WriteLine("\nInsert 3:"); 
  
    // "3" insert into its original  
    // position when the List is  
    // sorted 
    int index = Geek.BinarySearch(3); 
      
  
    if (index < 0)  
    { 
        Geek.Insert(~index, 3); 
    } 
  
    foreach(int g in Geek) 
    { 
          
        // prints the sorted list 
        // after inserting "3" 
        Console.WriteLine(g); 
          
    } 
} 
} 
  
// Driver Class 
public class search { 
      
    public static void Main() 
    { 
          
        // List creation 
        GFG gg = new GFG(); 
          
        List<int> Geek = new List<int>() { 
                              5, 6, 1, 9}; 
                                
        Console.WriteLine("Original List"); 
      
        foreach(int g in Geek) 
        { 
            Console.WriteLine(g); 
            // prints original List 
        } 
      
        Console.WriteLine("\nList in Sorted form"); 
        Geek.Sort(); 
      
        foreach(int g in Geek) 
        { 
            Console.WriteLine(g); 
            // prints the sorted List 
        } 
      
        // calling the method "binarySearch" 
        gg.binarySearch(Geek); 
    } 
}
输出:
Original List
5
6
1
9

List in Sorted form
1
5
6
9

Insert 3:
1
3
5
6
9
BinarySearch(T)方法

此方法使用指定的比较器在整个排序列表中搜索元素,并返回搜索到的元素的从零开始的索引。


用法:

public int BinarySearch (T item, System.Collections.Generic.IComparer<T> comparer);

参数:

  • item :这是要查找的项目,对于引用类型,该项目的值可以为null。
  • comparer :比较元素时使用的是IComparer <T>实现。

返回值:如果找到了项,则此方法返回要搜索的元素的从零开始的索引,如果找不到,则返回一个负数,该负数是大于元素的下一个元素的索引的按位补码,或者没有更大的元素,Count的按位补码。

异常:如果比较器为null,并且默认比较器Default找不到类型T的IComparable <T>通用接口或IComparable接口的实现,则此方法将提供InvalidOperationException。

以下示例程序旨在说明上述方法的用法:

范例1:

// C# program to demonstrate the  
// List<T>.BinarySearch(T,  
// IComparer<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 
    } 
} 
  
// Driver Class 
class geek { 
  
    // Main Method 
    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(); 
  
         // sort the list 
        list1.Sort(gg); 
         
        // prits the sorted form of original list 
        Console.WriteLine("\nList in sorted form"); 
  
        foreach(string g in list1) 
        { 
            Console.WriteLine(g); 
        } 
  
        //"D" is going to insert 
        //"gg" is the IComparer 
        int index = list1.BinarySearch("D", gg); 
         
        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); 
        } 
    } 
}
输出:
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

范例2:在本示例中,将使用一些整数值创建列表,并使用用户定义函数使用BinarySearch(T,Comparer <T>)方法在列表中插入新的整数。

// C# program to demonstrate the  
// List<T>.BinarySearch(T,  
// IComparer<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); 
    } 
} 
   
// Driver Class 
class geek { 
  
    // Main Method 
    public static void Main() 
    { 
        // list creation 
        List<int> list1 = new List<int>() { 
                               5, 6, 1, 9}; 
   
        // prints Original list 
        Console.WriteLine("Original string"); 
  
        foreach(int g in list1) 
        { 
            Console.WriteLine(g); 
        } 
   
         // creating object of class GFG 
        GFG gg = new GFG(); 
       
        // sort the list 
        list1.Sort(gg); 
          
        // 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) 
    { 
  
        // creating object of class GFG 
        GFG gg = new GFG(); 
   
        // "3" is going to insert 
        // "gg" is the IComparer 
        int index = list1.BinarySearch(3, gg); 
          
        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); 
        } 
    } 
}
输出:
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
BinarySearch(Int32,Int32,T,IComparer <T>)

此方法用于使用指定的比较器在排序后的List <T>中的元素范围内搜索元素,并返回该元素的从零开始的索引。

用法:

public int BinarySearch (int index, int count, T item, System.Collections.Generic.IComparer<T> comparer);

参数:

  • index:它是要搜索范围的从零开始的索引。
  • count:这是搜索范围的长度。
  • item:这是要定位的对象。对于引用类型,该值可以为null。
  • comparer:这是IComparer比较元素时使用的实现,或使用默认比较器Default的null。

返回值:如果找到该项目,它将返回排序后的List <T>中该项目的从零开始的索引;否则,返回0。否则为负数,它是大于元素的下一个元素的索引的按位补数,或者,如果没有更大的元素,则为Count的按位补数。

异常:

  • ArgumentOutOfRangeException:如果索引小于0或计数小于0。
  • ArgumentException:如果索引和计数不代表有效范围。
  • InvalidOperationException:如果比较器为null。

例:

// C# program to demonstrate the  
// List<T>.BinarySearch(Int32,  
// Int32, 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 search { 
      
// "binarySearch" function 
public void binarySearch(List<int> list1, 
                                  int i) 
{ 
    Console.WriteLine("\nBinarySearch a "+ 
                   "range and Insert 3"); 
      
    // "gg" is the object of class GFG 
    GFG gg = new GFG(); 
      
    // binary search 
    int index = list1.BinarySearch(0, i, 
                                 3, gg); 
  
  
    if (index < 0) 
    { 
          
        // insert "3" 
        list1.Insert(~index, 3); 
        i++; 
    } 
      
    Display(list1); 
} 
  
// "Display" function  
public void Display(List<int> list)  
{ 
      
    foreach( int g in list ) 
    { 
        Console.WriteLine(g); 
    } 
} 
} 
  
// Driver Class 
class geek 
{ 
      
    // Main Method 
    public static void Main() 
    { 
        List<int> list1 = new List<int>() 
        { 
            // list elements 
            15,4,2,9,5,7,6,8,10 
              
        }; 
      
        int i = 7; 
        Console.WriteLine("Original List"); 
          
        // "d" is the object of  
        // the class "search" 
        search d = new search(); 
          
        // prints Original list 
        d.Display(list1); 
      
        // "gg" is the object  
        // of class GFG  
        GFG gg = new GFG(); 
          
        Console.WriteLine("\nSort a range with "+ 
                       "the alternate comparer"); 
          
        // sort is happens between 
        // index 1 to 7             
        list1.Sort(1, i, gg); 
          
        // prints sorted list 
        d.Display(list1); 
          
        // call "binarySearch" function 
        d.binarySearch(list1,i); 
          
    } 
}
输出:
Original List
15
4
2
9
5
7
6
8
10

Sort a range with the alternate comparer
15
2
4
5
6
7
8
9
10

BinarySearch a range and Insert 3
15
2
3
4
5
6
7
8
9
10

注意:

  • 如果List <T>包含多个具有相同值的元素,则该方法仅返回一个事件,并且它可能返回任何一个事件,而不一定返回第一个。
  • List <T>必须已经根据比较器实现进行了排序;否则,结果不正确。
  • 此方法是O(log n)运算,其中n是范围内的元素数。

参考:



相关用法


注:本文由纯净天空筛选整理自SoumikMondal大神的英文原创作品 List BinarySearch() Method in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。