#Binary search

6 messages · Page 1 of 1 (latest)

sonic onyx
#

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;
    }
hasty mangoBOT
#

This post has been reserved for your question.

Hey @sonic onyx! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

sacred geyser
#

if less than, then we only iterate thru the first half until found, and if greater than, we iterate thru the second half.
iteration would be linear search. pure binary search keeps splitting the set of values in half

sonic onyx
#

ohhhh i read the def wrong thank you

hasty mangoBOT
# sonic onyx ohhhh i read the def wrong thank you

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.