2

我正在尝试在 Java 中实现二进制搜索,但不起作用...不知道为什么,它总是给我一个错误,说找不到数字...

我不知道为什么,我没有看到任何错误:S 感谢您的帮助...

public void busquedaBinaria(int[] arreglo, int buscar) {        

        int centro = 0; //middle
        int inferior = 0;
        int superior = arreglo.length - 1;
        boolean encontrado = false; //found flag

        while(inferior <= superior)
        {
            centro = (superior + inferior) / 2;            

              if (arreglo[centro] == buscar){
                  System.out.println("-Number " + buscar + " found in the " + centro + " position.");
                  encontrado=true;
                  break;
              }
              else if (arreglo[centro] > buscar) {
                  superior = centro - 1;
              }
              else{
                  inferior = centro + 1;
              }     
              System.out.println(centro);
        }

        if (encontrado == false) {
            System.out.println("-Number " + buscar + " hasn't been found.");
        }
    }
4

3 回答 3

4

您可以使用Arrays#binarySearchor Collections#binarySearch,它们已在库中可用。

于 2012-10-15T06:02:08.627 回答
1

这是我的贡献:

public class BinarySearch
{
   private static String search( String[] entries, String entry, int left, int right )
   {
      int index = ( left + right ) / 2;
      if( left > right || index >= entries.length )
      {
         return null;
      }
      int cmp   = entries[index].compareTo( entry );
      if( cmp == 0 )
      {
         return entry;
      }
      if( cmp > 0 )
      {
         return search( entries, entry, left, index - 1 );
      }
      return search( entries, entry, index + 1, right );
   }// String search( String[] entries, String entry, int left, int right )



   public static String search( String[] entries, String entry )
   {
      return search( entries, entry, 0, entries.length );
   }// String search( String[] entries, String entry )



   public static void main( String[] args )
   {
      String[] entries = new String[] { "Aubin", "Barbara", "George", "Muriel", "Sarah", "Tom" };
      for( String entry : entries )
      {
         System.out.println( search( entries, entry ));
      }
      System.out.println( search( entries, "Toto" ));
   }

}
于 2012-10-15T06:17:31.570 回答
1

二进制搜索仅适用于已排序的数字。请确保数组arreglo已排序。

如果您的数组按降序排列,那么您必须稍微更改逻辑。

     if (arreglo[centro] == buscar){
       System.out.println("-Number " + buscar + " found in the " + centro + " position.");
       encontrado=true;   
       break; 
     } 
     else if (arreglo[centro] > buscar) { 
       superior = centro + 1;
     }
     else{ 
       inferior = centro - 1; 
     }      
于 2012-10-15T06:14:21.167 回答