代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TwoSearch
{
class Data
{
int[] list;
int lower;
int upper;
int middle;
int count = 0; //记录比较次数
public Data(int max)
{
list = new int[max];
for (int i = 0; i < max; i++)
{
list[i] = i;
}
lower = 0;
upper = list.Length - 1;
}
public int Find(int t)
{
while (lower <= upper) //必须要有"="号,否则某些数字可以查找,但无法输出
{
count = count + 1;
middle = (lower + upper) / 2;
if (t == list[middle])
return middle;
else if (t > list[middle])
lower = middle + 1; //变更起始位置
else
upper = middle; //变更总长度
}
return -1; //没找到
}
public void GetCount()
{
Console.WriteLine("比较次数:" + count);
}
public void Size()
{
Console.WriteLine("数组长度:"+upper);
}
/// <summary>
/// 各项数组值
/// </summary>
public void Display()
{
for (int i = 0; i < upper; i++)
{
Console.WriteLine("值:"+list[i]);
}
Console.ReadLine();
}
}
class Program
{
static void Main(string[] args)
{
//此处注意数值不能越界
Data data = new Data(100000);
Console.WriteLine("查找数字:"+data.Find(6));
data.GetCount();
data.Size();
data.Display();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TwoSearch
{
class Data
{
int[] list;
int lower;
int upper;
int middle;
int count = 0; //记录比较次数
public Data(int max)
{
list = new int[max];
for (int i = 0; i < max; i++)
{
list[i] = i;
}
lower = 0;
upper = list.Length - 1;
}
public int Find(int t)
{
while (lower <= upper) //必须要有"="号,否则某些数字可以查找,但无法输出
{
count = count + 1;
middle = (lower + upper) / 2;
if (t == list[middle])
return middle;
else if (t > list[middle])
lower = middle + 1; //变更起始位置
else
upper = middle; //变更总长度
}
return -1; //没找到
}
public void GetCount()
{
Console.WriteLine("比较次数:" + count);
}
public void Size()
{
Console.WriteLine("数组长度:"+upper);
}
/// <summary>
/// 各项数组值
/// </summary>
public void Display()
{
for (int i = 0; i < upper; i++)
{
Console.WriteLine("值:"+list[i]);
}
Console.ReadLine();
}
}
class Program
{
static void Main(string[] args)
{
//此处注意数值不能越界
Data data = new Data(100000);
Console.WriteLine("查找数字:"+data.Find(6));
data.GetCount();
data.Size();
data.Display();
}
}
}