【问题标题】:Binary Search - display results二分搜索 - 显示结果
【发布时间】:2011-05-22 01:16:33
【问题描述】:
    public void Find() {

    String Value = "";
    System.out.println("Search Name");
            Value = Input.next();

    int Begin, End, Pivot;

    Begin = 0;
    End = CurrentCount;

    while(End - Begin > 1 ) {
        Pivot = Begin + (End - Begin)/2;

        if(Value.equals(ArrayList[Pivot].LastNamePlayer))
         System.out.println(ArrayList[Pivot].NamePerson);

        else if(Value.compareTo(ArrayList[Pivot].LastNamePlayer) < 0)
            End = Pivot;
        else
            Begin = Pivot;
        }
       if (Value.equals(ArrayList[Begin].LastNamePlayer))
            System.out.println(ArrayList[Begin].NamePerson );
           else if(Value.equals(ArrayList[End].LastNamePlayer))
             System.out.println(ArrayList[End].NamePerson);
           else
          System.out.println("Not Found!");
    }

看起来这将在数组中找到正确的记录。问题是它进入了一个无限循环,打印出结果。显示结果的最佳方式是什么?

【问题讨论】:

    标签: java infinite-loop binary-search


    【解决方案1】:

    当你找到匹配时你需要打破:

    if(Value.equals(ArrayList[Pivot].LastNamePlayer))
    {
        System.out.println(ArrayList[Pivot].NamePerson);
        break;
    }
    

    【讨论】:

      【解决方案2】:

      添加退货;到 if found 和 else 语句的末尾。它将终止while循环并结束函数。

      if (Value.equals(ArrayList[Begin].LastNamePlayer)){
          System.out.println(ArrayList[Begin].NamePerson );
          return;
      }
      else if(Value.equals(ArrayList[End].LastNamePlayer))
          System.out.println(ArrayList[End].NamePerson);
          return;
      else
          System.out.println("Not Found!");
          return;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-10-09
        • 1970-01-01
        • 1970-01-01
        • 2021-01-25
        • 2023-04-07
        • 2013-01-14
        • 2014-01-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多