已排序数组中的二进制搜索

时间:2017-10-10 09:43:15

标签: arrays binary-search

您好我正在尝试通过使用用户通过文本框输入来在排序数组中执行二进制搜索。

这是我的代码:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms;

namespace arra3 {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int[] arr = { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 };

        int low, high, user_input, mid;

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

            user_input = Convert.ToInt32(textBox1.Text);

            while (low <= high)
            {
                mid = (low + high) / 2;


                if (arr[mid] < user_input)
                {
                    low = mid + 1;
                    continue;
                }
                else if (arr[mid] > user_input)
                {
                    high = mid - 1;
                    continue;
                }

                else
                {
                    MessageBox.Show(mid.ToString());
                }
            }
            MessageBox.Show("-1".ToString());

        }
    } 
}

但是我继续得到-1作为输出,或者如果输入零则输入0的无限循环。

请帮忙吗?

1 个答案:

答案 0 :(得分:0)

我已初始化lowhigh个变量,并在找到匹配项后添加了return语句。 这是更正的代码(注意评论):

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms;

namespace arra3 {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int[] arr = { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 };

        int low, high, user_input, mid;

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

            user_input = Convert.ToInt32(textBox1.Text);
            low = 0;  // <- HERE
            high = arr.Length;  // <- HERE

            while (low <= high)
            {
                mid = (low + high) / 2;


                if (arr[mid] < user_input)
                {
                    low = mid + 1;
                    continue;
                }
                else if (arr[mid] > user_input)
                {
                    high = mid - 1;
                    continue;
                }

                else
                {
                    MessageBox.Show(mid.ToString());
                    return;  // <- HERE
                }
            }
            MessageBox.Show("-1".ToString());

        }
    } 
}