0

In my program, I store 20 names from a file into an array. The user can then input a name and a binary search is used to find the position. My program can't seem to match the target to the array midpoint. I've tried trimming any white space but still no luck. Does the search algorithm look ok?

while(true){
            System.out.println("Enter the name you are searching for.");
            String target = sc.nextLine();
            if(target.equals("done"))
                break;
            int mid;
            int left = 0;
            int right = names.length-1;
            while(left <= right){
                mid = (left + right)/2;
                if(target.equals(names[mid].trim())){
                    System.out.println("Found in position: " + mid);    //when found
                    break;
                }
                else if(target.compareTo(names[mid]) < 0){       //set right parameter
                    right = mid-1;
                }
                else if(target.compareTo(names[mid]) > 0){      //set left parameter
                    left = mid+1;    
                }         
            }
        }
2
  • Maybe it's a dumb question but names is sorted in ascending order right ? the algorithm looks fine. Commented Nov 28, 2013 at 4:50
  • Try: String target = sc.nextLine().trim(); Commented Nov 28, 2013 at 4:56

2 Answers 2

1

Maybe you should trim target too?

if(target.trim().equals(names[mid].trim())){
                System.out.println("Found in position: " + mid);    //when found
                break;
            }
Sign up to request clarification or add additional context in comments.

Comments

0

Make sure the array names is sorted, because binary searching only works in sorted array.

The algorithm is OK.

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.