簡體   English   中英

排序數組中的二進制搜索

[英]binary search in sorted array

嗨,我正在嘗試通過用戶通過文本框使用輸入在排序數組中執行二進制搜索。

這是我的代碼:

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的無限循環。

有什么幫助嗎?

找到匹配后,我已經初始化了low變量和high變量並添加了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());

        }
    } 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM