马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace task4
{
class Program
{//二分法递归
List<int> l = new List<int>();
public int BinarySearch(List<int> l,int start,int end,int x)
{
if (start <= end)
{
if (l.Count == 0)
return -1;
int mid = l.Count / 2;
if (l[mid] == x)
return mid;
else if (x < l[mid])
return BinarySearch(l, start, mid - 1, x);
else
{
return BinarySearch(l, mid + 1, end, x);
}
}
return -1;
}
static void Main(string[] args)
{
Program pro = new Program();
int[] sortedData = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
for (int i = 0; i < sortedData.Length; i++)
{
pro.l.Add(sortedData[i]);
}
int length = pro.l.Count();
int key = 5;
int value =pro.BinarySearch(pro.l, 0, length - 1, key);
Console.WriteLine("found in pos"+value);
}
}
}
|