Java基础之一组有用的类——使用二叉树搜索算法搜索某个作者(TryBinarySearch)

控制台程序。

Arrays类中的binarySearch()静态方法使用二叉树搜索算法,在有序数组中查找包含给定值的元素。只有当数组的元素按升序方式排序时,该方法才是最有效的,否则就应在调用binarySearch()方法之前调用sort()方法。

binarySearch()方法的所有版本都返回int类型的值,也就是在array中找到value的索引位置。当然,value也可能不在数组中,此时返回一个负整数。计算过程是:提取大于value的第一个元素的索引位置,翻转元素的取值符号后再减1.

 1 public class Person implements Comparable<Person> {
 2   // Constructor
 3   public Person(String firstName, String surname) {
 4     this.firstName = firstName;
 5     this.surname = surname;
 6   }
 7 
 8   @Override
 9   public String toString() {
10     return firstName + " " + surname;
11   }
12 
13   // Compare Person objects
14   public int compareTo(Person person) {
15     int result = surname.compareTo(person.surname);
16     return result == 0 ? firstName.compareTo(person.firstName) : result;
17   }
18 
19   public String getFirstName() {
20     return firstName;
21   }
22 
23   public String getSurname() {
24     return surname;
25   }
26   private String firstName;                                            // First name of person
27   private String surname;                                              // Second name of person
28 }
 1 import java.util.Arrays;
 2 
 3 public class TryBinarySearch {
 4   public static void main(String[] args) {
 5     Person[] authors = {
 6             new Person("Danielle", "Steel"), new Person("John", "Grisham"),
 7             new Person("Tom", "Clancy"),     new Person("Christina", "Schwartz"),
 8             new Person("Patricia", "Cornwell"), new Person("Bill", "Bryson")
 9                        };
10 
11 
12     Arrays.sort(authors);                                              // Sort using Comparable method
13 
14     System.out.println("
Order after sorting into ascending sequence:");
15     for(Person author : authors) {
16       System.out.println(author);
17     }
18 
19     // Search for authors
20     Person[] people = {
21          new Person("Christina", "Schwartz"),    new Person("Ned", "Kelly"),
22          new Person("Tom", "Clancy"),        new Person("Charles", "Dickens")
23                       };
24      int index = 0;
25     System.out.println("
In search of authors:");
26     for(Person person : people) {
27       index = Arrays.binarySearch(authors, person);
28       if(index >= 0) {
29         System.out.println(person + " was found at index position " + index);
30       } else {
31         System.out.println(person + " was not found. Return value is " + index);
32       }
33     }
34   }
35 }
原文地址:https://www.cnblogs.com/mannixiang/p/3438746.html