package binarysearch;
import java.util.*;
import java.io.*;
public class BinarySearch {
public static void main(String[] args) {
int i;
LinkedList list = new LinkedList();
// Create a list of students, together with their room numbers.
list.add(new Student("Fred Bloggs",10));
list.add(new Student("Adam Smith",20));
list.add(new Student("Gordon Bennett",31));
list.add(new Student("Raquel Welsh",42));
list.add(new Student("Meg Ryan",53));
list.add(new Student("Julia Roberts",60));
list.add(new Student("Dopy",7));
list.add(new Student("Sleepy",8));
list.add(new Student("Snow White",9));
// Sort the list
Collections.sort(list);
// Create a temporary student with no name, just room 42
// (since the compareTo method is only looking at the room number)...
Student s = new Student(" ",42);
// get the index of who is staying at room 42
i = Collections.binarySearch(list,s);
// and retrieve the student from the list
Student who = (Student) list.get(i);
// Print out who is actually staying at room 42
System.out.println("The student staying in room 42 is :"+who.getName());
}
}
class Student implements Comparable{
private int roomNumber;
private String name;
public Student(String name, int roomNumber) {
this.roomNumber = roomNumber;
this.name = name;
}
public String getName() {
return name;
}
public int getRoom() {
return roomNumber;
}
public int compareTo(Object o) {
Student s = (Student) o;
if(s.roomNumber < roomNumber) {
return 1;
} else if (s.roomNumber == roomNumber) {
return 0;
} else {
return -1;
}
}
} |