在C#中的二进制搜索数组

在本文中,我将解释如何在数组中进行二进制搜索。

在这个c# 程序中使用了数组二进制搜索方法。
它使用到了排序和搜索算法。
其中 BinarySearch方法有一个接受类型参数的版本,可以在尖括号中指定类型参数。

namespace demo_array

{
  class Program

  {     
      static void Main(string[] args)
      {
          string[] arr = new string[5];

          arr[0] = "abc";
          arr[1] = "pqr";
          arr[2] = "ajay";
          arr[3] = "Raju";

          arr[4] = "apple";
          int i;
          Array.Sort(arr);
          for (i = 0; i < arr.Length; i++)

          {
              Console.WriteLine("The item " + arr[i] + " found at " + i);
          }
          //Find an item        

          object name = "Raju";
          int nameIndex = Array.BinarySearch(arr, name);
          if (nameIndex >= 0)
              Console.WriteLine("<br>"+"Item was at " + nameIndex.ToString() + "th position");

          else
              Console.WriteLine("<br>"+"Item not found");
          Console.ReadKey();        
      }

  }
}
日期:2020-04-11 22:50:14 来源:oir作者:oir