problem with binarysearch algorithm

Posted by arash on Stack Overflow See other posts from Stack Overflow or by arash
Published on 2010-12-25T09:29:57Z Indexed on 2010/12/25 9:54 UTC
Read the original article Hit count: 259

Filed under:
|
|

hi friends,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;
        int mid = (int)Math.Floor(nums.Length / 2.0);

        while (1<= nums.Length)
        {


            if (searchnum < nums[mid])
            {
                last = mid - 1;
            }
            if (searchnum > nums[mid])
            {
                first = mid + 1;
            }
            else
            {
                return nums[mid];

            }
        }
        return -1; 


    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about algorithm