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

控制台程序。

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

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

 public class Person implements Comparable<Person> {
// Constructor
public Person(String firstName, String surname) {
this.firstName = firstName;
this.surname = surname;
} @Override
public String toString() {
return firstName + " " + surname;
} // Compare Person objects
public int compareTo(Person person) {
int result = surname.compareTo(person.surname);
return result == 0 ? firstName.compareTo(person.firstName) : result;
} public String getFirstName() {
return firstName;
} public String getSurname() {
return surname;
}
private String firstName; // First name of person
private String surname; // Second name of person
}
 import java.util.Arrays;

 public class TryBinarySearch {
public static void main(String[] args) {
Person[] authors = {
new Person("Danielle", "Steel"), new Person("John", "Grisham"),
new Person("Tom", "Clancy"), new Person("Christina", "Schwartz"),
new Person("Patricia", "Cornwell"), new Person("Bill", "Bryson")
}; Arrays.sort(authors); // Sort using Comparable method System.out.println("\nOrder after sorting into ascending sequence:");
for(Person author : authors) {
System.out.println(author);
} // Search for authors
Person[] people = {
new Person("Christina", "Schwartz"), new Person("Ned", "Kelly"),
new Person("Tom", "Clancy"), new Person("Charles", "Dickens")
};
int index = 0;
System.out.println("\nIn search of authors:");
for(Person person : people) {
index = Arrays.binarySearch(authors, person);
if(index >= 0) {
System.out.println(person + " was found at index position " + index);
} else {
System.out.println(person + " was not found. Return value is " + index);
}
}
}
}
上一篇:DOM解析XML文件实例


下一篇:Response对象