简体   繁体   中英

Binary Search - display results

    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!");
    }

It looks like this will locate the proper record in the array. The problem is that it goes into an infinite loop printing out the result. What is the best way to display the result?

You need to break when you find the match:

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

Add a return; to the end of your if found and to the end of your else statement. It will terminate the while loop and end the function.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM