使用数组2
时间:2010-09-26 来源:草珊瑚
使用数组>查找数组>BinarySearch二进制搜索
BinarySearch找到匹配的元素值,返回指定元素的索引。找不到,返回一个负值。
代码 using System;using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//查找数组>BinarySearch二进制搜索
string[] csharpBooks = new string[3];
csharpBooks[0] = "book1";
csharpBooks[1] = "book3";
csharpBooks[2] = "book2";
Array.Sort(csharpBooks);//BinarySearch要求搜寻的数组必须先排序,并且按升序排序。数组中的每个元素要实现IComparable接口
foreach (string csharpBook in csharpBooks)
{
Console.WriteLine(csharpBook);
}
Console.WriteLine("使用二分算法搜寻数组元素值book2:");
object searchBook = "book2";
int searchResult = Array.BinarySearch(csharpBooks, searchBook);
if (searchResult < 0)
{
Console.WriteLine("搜寻数组元素值{0},没有找到!", searchBook);
}
else
{
Console.WriteLine("搜寻数组元素值{0},已找到,在索引位置{1}", searchBook, searchResult);
}
Console.ReadLine();
}
}
}
相关阅读 更多 +