2017-10-10 73 views
0

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

這是我的代碼:

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

請幫忙嗎?

+0

爲什麼不先製作樹結構? - https://msdn.microsoft.com/en-us/library/ms379572(v=vs.80).aspx – tommybee

+0

@MCPol答案已更新 –

+0

@MCPol,請將您的問題標記爲已回答(接受我的回答)。請閱讀這裏的規則:https://stackoverflow.com/help/someone-answers。非常感謝你。 –

回答

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()); 

     } 
    } 
} 
+0

對不起花了很長時間回答。是的,它確實有效。感謝您的幫助。非常感謝 –

+0

@MCPol,如果它幫助你,請將其標記爲答案 –