1.二分查找和顺序查找
二分查找:
class TestSearch
{
public static int BinarySearch(int[] arr, int target)
{
int l = 0;
int r = arr.Length - 1;
while (l <= r)
{
//int mid = (l + r) / 2; //l和r都是大整型时,可能会溢出
int mid = l + (r - l) / 2;
if (target < arr[mid])
{
r = mid - 1;
}
else if (target > arr[mid])
{
l = mid + 1;
}
else
{
return mid;
}
}
return -1;
}
}
2.查找算法性能比较
class Program
{
static void Main(string[] args)
{
string filename3 = "测试文件2/游戏会员表.txt";
string filename4 = "测试文件2/游戏用户表.txt";
int[] arr3 = TestSearch.ReadFile(filename3);
int[] arr4 = TestSearch.ReadFile(filename4);
Console.WriteLine("游戏会员数量:" + arr3.Length);
Console.WriteLine("调查用户数量:" + arr4.Length);
Console.WriteLine();
Stopwatch t3 = new Stopwatch();
Stopwatch t4 = new Stopwatch();
Console.WriteLine("顺序查找法");
t3.Start();
int sum3 = 0;
for (int i = 0; i < arr4.Length; i++)
{
int target = arr4[i];
if (TestSearch.OrderSearch(arr3, target) == -1)
sum3++;
}
t3.Stop();
Console.WriteLine("查找到:" + sum3 + "个普通玩家");
Console.WriteLine("运行时间:" + t3.ElapsedMilliseconds + "ms");
Console.WriteLine();
Console.WriteLine("二分查找法");
t4.Start();
Array.Sort(arr3);
int sum4 = 0;
for (int i = 0; i < arr4.Length; i++)
{
int target = arr4[i];
if (TestSearch.BinarySearch(arr3, target) == -1)
{
sum4++;
}
}
t4.Stop();