I think i understand the concept of binary search =?= we split the indices in half. we then check a value, in this case the book id (we assume id and list are ordered , naturally). so split indices in half, check if id at middle is less than, greater, than or equal to the ID we need(searchedId) . if less than, then we only iterate thru the first half until found, and if greater than, we iterate thru the second half.
i attempted to put this into code and made a mess. Book class is shown in case needed
Note that in the case of books, you are examining the values of the books' id-variable. Meaning that in this exercise, instead of examining the value at an index, you should examine the value of the id-variable of the value found at the index.
public class Book {
private int id;
private String name;
public Book(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "(id: " + id + "; name: " + name + ")";
}
}
public static int binarySearch(ArrayList<Book> books, long searchedId) {
long middle = (int) books.size() / 2;
if (books.get((int)middle).getId() < books.get((int)searchedId).getId()) {
for (int i = (int) middle; i < books.size(); i++) {
if (books.get(i) == books.get((int)searchedId)) {
return i;
}
}
}
if (books.get((int)middle).getId() > books.get((int)searchedId).getId()) {
for (int i = 0; i <= (int) middle; i++) {
if (books.get(i) == books.get((int)searchedId)) {
return i;
}
}
}
return -1;
}