您的位置:首页 > 编程语言 > C#

c# 二分查找法(2分钟算法)

2015-11-05 23:47 351 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication14
{
class Program
{
static void Main(string[] args)
{
int sequence = 0;
List<int> ints = new List<int>()
{
9,832,32,2,1,10,4

};
while (true)
{
Console.WriteLine("请输入要查找的值:");
bool found = false;
int a = int.Parse(Console.ReadLine());
int mid = 0;
int i = 0;
int j = ints.Count - 1;
while (i < j)
{
if (i == j && ints[i] != a)
{
break;

}
mid = (i + j) / 2;
if (ints[mid] == a)
{
sequence = mid;
found = true;
break;
}
if (ints[mid] > a)
{
i = mid + 1;

}
else
{
j = mid - 1;

}

}
if (found)
{
Console.WriteLine("找到:" + a + " 在序号" + (sequence+1));
}
else
{
Console.WriteLine("没找到。");
}
}
Console.ReadKey();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: