Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

the code below belongs to binary search algorithm,user enter numbers in textbox1 and enter the number that he want to fing with binarysearch in textbox2.i have a problem with it,that is when i enter for example 15,21 in textbox1 and enter 15 in textbox2 and put brakpoint on the line i commented below,and i understood that it doesnt put the number in textbox2 in searchnums(commented),for more explanation i comment in code.thanks in advance

 public void button1_Click(object sender, EventArgs e)
    {


        int searchnums = Convert.ToInt32(textBox2.Text);//the problem is here,the value in textbox2 doesnt exist in searchnums and it has value 0. 

        int result = binarysearch(searchnums);
        MessageBox.Show(result.ToString());
    }
    public int binarysearch(int searchnum)
    {
        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 first =0;

        int last = nums.Length-1;


        while (1<= nums.Length)
        {
        int mid = (int)Math.Floor(first+last / 2.0);
             if (first > last)
            {
                break;
            }
            if (searchnum < nums[mid])
            {
                last = mid - 1;
            }
            if (searchnum > nums[mid])
            {
                first = mid + 1;
            }
            else
            {
                return nums[mid];

            }
        }
        return -1; 


    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
165 views
Welcome To Ask or Share your Answers For Others

1 Answer

First, when you know you can place a breakpoint on a line, you sure know you can step through the whole program and see what values are in each variable or property. So, go ahead, and debug. Among other things you are probably missing data input validation in your program.

Second, your binary search implementation is missing mid recalculation after first or last is updated and a stop condition in case the number being looked for is not found in the array. You have to break the loop in case first == last, regardless if nums[mid] matches or not — nobody said the number from textbox2 must be in the array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...