0

I want to make my own binary search algorithm to search ArrayList of 1 000 000 elements. I decided to do the search with do-while loop. I am aware I could use while() loop. But when I run it, it takes much time to find the number. I guess something is wrong with setting the value of first and last element of ArrayList. My code is

import java.util.*;

public class BinSearchAlg {
public static void main(String[]args){

    int first;
    int last;
    int median;//middle element of arraylist
    Long element;//element with median index
    Scanner scan = new Scanner(System.in);
    ArrayList<Long>list = new ArrayList();
    for(long l=0;l<1000000;l++){
        list.add(l);//list is sorted
    }
    first = 0;
    last = list.size();
    median = (last-first)/2;
    element = list.get(median);
    System.out.println("Choose the number: ");
    long l = scan.nextLong();
    do{
        if(element<l){
            first = median;
            median=(last-first)/2;
            element = list.get(median);
        }else{ //if(element>l){
            last = median;
        median = (last-first)/2;
        element = list.get(median);
        }
    }while(element!=l);
}
}

Thanks for you help.

3 Answers 3

2

The median calculation is problematic:

median=(last-first)/2;

You should rather do:

median=(last+first)/2;

In the current code you have, when you are searching in the range [10..16], your code will try to compare the goal with the median of list.get(3).

There could be another bug, but for now I'll leave you with this. Hint: try [0, 1], which should expose the bug in the code.

Sign up to request clarification or add additional context in comments.

7 Comments

And first = median + 1; instead of just median. Further while (first < last).
@JoopEggen yeah, I didn't give OP the answer, but added a hint.
@UmNyobe um, any reason for using that? Could it work without set fst = med + 1?
@ZiyaoWei If the list is large enough, first + last can overflow. (last - first)/2 + first, or, as UmNyobe wrote, (first - last)/2 + last cannot overflow (for 0 <= first <= last).
@DanielFischer Ah I see. Thanks! (Although before overflowing, the memory probably ran out first under most circumstances, and we can always use long8) )
|
0

As Ziyao Wei answered, you'll need to fix the median. In addition, you'll probably need a different loop exit condition - right now you've got an infinite loop if l isn't in the list. Also, your if-else needs to be an if-elseif-else - at present if l == element then the loop will actually treat this as element > l and continue looping.

5 Comments

Ok, I used median=((last-first)/2)+first in my code. I also used if(element>l){last = median-1; ...}, then I added else if(element==l){break;} and else if(!list.contains(l)){break;} and used while(first<last); instead of while(element!=l); Now it seems it works. What do you think?
Take out !list.contains(1) - this will do a linear search of the entire list. Instead, replace it with else break; to exit the loop when you've found the element.
Done. Is the rest of the code right? Does binary search work now?
I think your code should return a boolean to indicate whether the element was found. Other than that it looks like it's ready for testing.
When I type any number in the range of the list, program will finish after a few miliseconds - in addition I used System.currentTimeMillis() method to count how much time has been taken between choosing the number and finding it.
0

You can directly use Collection class's binary search method present java.util package :-

Collections.binarySearch(myList,key.get(i),new MyTransferObjectClass());

and

public class MyTransferObjectClass implements Comparator<MyTransferObjectClass>{

@Override
    public int compare(MyTransferObjectClass o1, MyTransferObjectClass o2) {
                //your logic for comparison
    }

}

why to add redundant code when you can use available APIs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.