您的位置:首页 > 其它

二分法算法

2020-02-03 02:29 337 查看

 

 

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{

int[] iArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
for (int i = 0; i < iArray.Length; i++)
Console.Write(iArray[i] + ",");
Console.WriteLine("请输入您要查找的数字:");
int ikey = Convert.ToInt32(Console.ReadLine());
Program bs = new Program();
int iResult = bs.iBinarySearch(ikey, iArray);
Console.WriteLine(iResult);
Console.ReadLine();
return;
}

public int iBinarySearch(int key, int[] iArray)
{
int iLeft = 0;
int iRight = iArray.Length - 1;
while (iLeft <= iRight)
{
int iMiddle = (iLeft + iRight) / 2;
if (key == iArray[iMiddle])
return iMiddle;
else if (key > iArray[iMiddle])
iLeft = iMiddle + 1;
else
iRight = iMiddle - 1;
}
return -1;
}
}
}
[/code]

  

转载于:https://my.oschina.net/martin321/blog/1525321

  • 点赞
  • 收藏
  • 分享
  • 文章举报
choupo1919 发布了0 篇原创文章 · 获赞 0 · 访问量 317 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
-->
新的分享
章节导航