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;
}
}
}
namesis sorted in ascending order right ? the algorithm looks fine.String target = sc.nextLine().trim();