【问题标题】:problem with binarysearch(calculate the first,last,mid with the new values)二进制搜索的问题(用新值计算第一个,最后一个,中间)
【发布时间】:2010-12-25 16:58:40
【问题描述】:

下面的代码属于二分查找算法。用户在 textbox1 中输入数字,然后在 textbox2 中输入他想用二进制搜索找到的数字。 现在我有一个问题,我想当 mid,first,last 的值再次改变时开始函数。我的意思是例如:当 last=mid-1;该函数再次开始并使用 last 的新值进行计算(我在代码中注释以获得更多解释) 谢谢

 private void button1_Click(object sender, EventArgs e)
    {
        string strsearchnums = textBox2.Text;
        int result = binarysearch(strsearchnums);
        textBox14.Text = result.ToString();
    }
    public int binarysearch(string strsearchnum)
    {
        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 searchnum = Convert.ToInt32(strsearchnum);
        int first = nums.First();

        int last = nums.Last();

        while (1 <= nums.Length - 1)
        {
            int mid = (int)Math.Floor(nums.Length / 2.0) - 1;

            if (nums[0]> nums[nums.Length-1])
            {
                break;
           }

            if (searchnum < nums[mid])
            {
                last = mid - 1;

         binarysearch(strsearchnum);       ///i thought i should do like this but this isnt correct it becomes stackoverflow    
            }
            if (searchnum > nums[mid])
            {
                first = mid + 1;
      binarysearch(strsearchnum);      ///i thought i should do like this but this isnt correct it becomes stackoverflow    
            }
            if (searchnum == nums[mid])
            {


              return nums[mid];


            }

        }

        return -1; 
    }

【问题讨论】:

    标签: c# windows binary-search


    【解决方案1】:

    首先,当用户在文本框中输入数字时,这些数字可能未排序,因此您需要首先对数组进行排序,因为二分搜索算法适用于排序后的序列。

       1- Splitt the string with ',' and store in the int[] array.
    
      string[] strArray = textBox1.Text.split(new string[]{","}, StringSplitOptions.RemoveEmptyEntries);
    
        List<int> lstInts = new List<int>();      
       foreach(string str in strArray)
       {
          int j;
          int k=0;
    
          if(int.TryParse(str,out j))
            {
               lstInts.Add(j);
            }
        }
         int[] bsArray = lstInts.ToArray();
    
       2- Now Sort the Array.
          Array.Sort(bsArray);
    
       3- Now use Array.Binaryearch() , if you wanna use  framework implementation which is optimized also
    
          Array.BinarySearch(bsArray, valueToBeSearched)
    
         if you don't wanna use Framework implementation than follow below algorithm
    
       public int DoBinarySearchNoNRecursively(int[] array, int value)
        {
            int high = array.Length - 1;
    
            int low = 0;
    
            while (low < high)
            {
                int mid = low + (high - low) / 2;
    
                if (value == array[mid])
                    return mid;
                else if (value > array[mid])
                    low = mid + 1;
                else if (value < array[mid])
                    high = mid;
    
            }
    
            return -1;
        }
    

    【讨论】:

      【解决方案2】:

      第一个问题是你永远不会改变 strsearchnum 的值——所以你总是会得到一个 Stackoverflow 异常,因为它是一个无限递归。通常,对于递归二进制搜索,您希望 binarySearch 方法传递您要查找的数字、最小值和最大值,并根据二进制搜索算法修改最小值和最大值。方法签名应该类似于

      int binarySearch(int min, int max, int num)
      {
      
      }
      

      这应该可以帮助您入门。

      【讨论】:

        【解决方案3】:

        我更正了下面的代码,它更正了:

         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;
                    }
                    if (searchnum == nums[mid])
                    {
                        return nums[mid];
                    }
                }
                return -1;
        
            }
        

        【讨论】:

          【解决方案4】:

          这就是 BinarySearch 的工作原理......

          二分查找算法比较多 比线性搜索有效 算法,但它要求 数组被排序。

              // perform a binary search on the data      
               public int binarysearch(string strsearchnum)
          {
          
              string[] source = textBox1.Text.Split(',');
              int[] data = new int[source.Length];
              for (int i = 0; i < source.Length; i++)
              {
                  data[i] = Convert.ToInt32(source[i]);
              }
          
          
            int low = 0 ; // low end of the search area                
            int high = data.length - 1 ; // high end of the search area
            int middle = ( low + high + 1 ) / 2 ; // middle element    
            int location = -1; // return value; -1 if not found        
          
            do // loop to search for element
               {
          
          
              // if the element is found at the middle               
               if ( searchElement == data[ middle ] )                 
              location = middle; // location is the current middle
          
              // middle element is too high                      
              else if ( searchElement < data[ middle ] )         
              high = middle - 1 ; // eliminate the higher half
              else // middle element is too low                  
              low = middle + 1 ; // eliminate the lower half  
          
              middle = ( low + high + 1 ) / 2 ; // recalculate the middle
              } while ( ( low <= high ) && ( location == -1 ) );            
          
              return location; // return location of search key
             } // end method binarySearch                         
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-01-14
            • 2023-03-21
            • 2021-11-18
            • 2022-07-07
            • 2023-01-18
            • 2013-02-14
            • 1970-01-01
            • 2020-08-23
            相关资源
            最近更新 更多