【发布时间】:2010-12-25 16:58:40
【问题描述】:
下面的代码属于二分查找算法。用户在 textbox1 中输入数字,然后在 textbox2 中输入他想用二进制搜索找到的数字。 现在我有一个问题,我想当 mid,first,last 的值再次改变时开始函数。我的意思是例如:当 last=mid-1;该函数再次开始并使用 last 的新值进行计算(我在代码中注释以获得更多解释) 谢谢
private void button1_Click(object sender, EventArgs e)
{
string strsearchnums = textBox2.Text;
int result = binarysearch(strsearchnums);
textBox14.Text = result.ToString();
}
public int binarysearch(string strsearchnum)
{
string[] source = textBox1.Text.Split(',');
int[] nums = new int[source.Length];
for (int i = 0; i < source.Length; i++)
{
nums[i] = Convert.ToInt32(source[i]);
}
int searchnum = Convert.ToInt32(strsearchnum);
int first = nums.First();
int last = nums.Last();
while (1 <= nums.Length - 1)
{
int mid = (int)Math.Floor(nums.Length / 2.0) - 1;
if (nums[0]> nums[nums.Length-1])
{
break;
}
if (searchnum < nums[mid])
{
last = mid - 1;
binarysearch(strsearchnum); ///i thought i should do like this but this isnt correct it becomes stackoverflow
}
if (searchnum > nums[mid])
{
first = mid + 1;
binarysearch(strsearchnum); ///i thought i should do like this but this isnt correct it becomes stackoverflow
}
if (searchnum == nums[mid])
{
return nums[mid];
}
}
return -1;
}
【问题讨论】:
标签: c# windows binary-search