运行这个C#写的二分法查找导致栈溢出了
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 == x)
return mid;
else if (x < l)
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);
}
int length = pro.l.Count();
int key = 5;
int value =pro.BinarySearch(pro.l, 0, length - 1, key);
Console.WriteLine("found in pos"+value);
}
}
}
单步调试下就能知道错误在哪{:10_256:}
页:
[1]