帶 C# 示例的 Array.BinarySearch(Array, Object) 方法


C# 中的 Array.BinarySearch(Array, Object) 方法用於使用陣列中每個元素以及指定物件實現的 IComparable 介面在整個一維已排序陣列中搜索特定元素。

語法

public static int BinarySearch (Array arr, object val);

上面,arr 是已排序的一維陣列,val 是要搜尋的物件。

示例

 線上示例

using System;
public class Demo {
   public static void Main() {
      int[] intArr = {5, 10, 15, 20};
      Array.Sort(intArr);
      Console.WriteLine("Array elements...");
      foreach(int i in intArr) {
         Console.WriteLine(i);
      }
      Console.Write("Element 25 is at index = " + Array.BinarySearch(intArr, 20));
   }
}

輸出

Array elements...
5
10
15
20
Element 25 is at index = 3

示例

 線上示例

using System;
public class Demo {
   public static void Main() {
      string[] strArr = {"John", "Tim", "Fedric", "Gary", "Harry", "Damien"};
      Array.Sort(strArr);
      Console.WriteLine("Array elements...");
      foreach(string s in strArr) {
         Console.WriteLine(s);
      }
      Console.Write("Element Gary is at index = " + Array.BinarySearch(strArr, "Gary"));
      Console.Write("
Element Tom is at index = " + Array.BinarySearch(strArr, "Tom"));    } }

輸出

Array elements...
Damien
Fedric
Gary
Harry
John
Tim
Element Gary is at index = 2
Element Tom is at index = -7

更新於:03-12-2019

133 次瀏覽

開啟你的 職業

完成該課程以獲取認證

開始
廣告
© . All rights reserved.