C# 如何用二分法查找

xin_bin 2012-03-27 03:37:28
输入一个数,在已经排序好的数组中查找是否存在和存在于数组什么位置
...全文
381 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
xin_bin 2012-03-28
  • 打赏
  • 举报
回复
已经解决了
dyx2010 2012-03-27
  • 打赏
  • 举报
回复
namespace BinaryTree
{
class Program
{
static int BinaryFind(int[] a, int b)
{
int low = 1;
int high = a.Length;
int mid;



while (low <=high)
{
mid = (low + a.Length)/2;
if (a[mid] > b)
high = mid-1;
else if (a[mid] < b)
low = mid+1;
else
return mid+1;
}
return 0;

}
static void Main(string[] args)
{
int[] a = new int[5] { 4, 6,9, 12, 18 };
int store;
store = Program.BinaryFind(a,12);
if (Convert.ToBoolean(store))
Console.WriteLine("{0}", store);
else
Console.WriteLine("没有要查找的数字");
}
}
}


}
static void Main(string[] args)
{
int[] a = new int[5] { 4, 6, 19, 2, 8 };
int store;
store = Program.BinaryFind(a,8);
if (Convert.ToBoolean(store))
Console.WriteLine("{0}", store);
else
Console.WriteLine("没有要查找的数字");
}
}
threenewbee 2012-03-27
  • 打赏
  • 举报
回复
简单地说,就是把这个数字先和数组1/2位置的那个比较,如果大了,和3/4的比较,如果小了和1/4的比较。
依此类推,每次寻找范围缩小1/2,直到查找到。
dyx2010 2012-03-27
  • 打赏
  • 举报
回复
int function(int a[] ,int b)
{


}
杨友山 2012-03-27
  • 打赏
  • 举报
回复
jion_tang88 2012-03-27
  • 打赏
  • 举报
回复
设定x,y分别标注查找的开始位置和结束位置,然后如(x+y)/2这个中间元素比较,
如果(x+y)/2>带查找元素(a)那么就在x--y(y = (x+y)/2)下查找
反之则在x(x = (x+y)/2)--y下查找 这么简单的
兔子丶哥 2012-03-27
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 bdmh 的回复:]
google "c# 二分法"
[/Quote]
bdmh 2012-03-27
  • 打赏
  • 举报
回复
google "c# 二分法"

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧