Reputation: 61
I have written binary search using a while loop. It searches for the matching name and prints their aim which is in a parallel array b[]
import java.util.*;
class binarysearch {
public static void calc() {
Scanner sc = new Scanner(System.in);
int l = 0, mid = 0, u = 4, i, f = 0;
String ns;
String a[] = { "Amar", "Camelia", "Debopriya", "Gargi", "Harmeet" };
String b[] = { "Astronaut", "Artist", "Dancer", "Singer", "Engineer" };
System.out.println("Enter name to be Searched");
ns = sc.next();
while (l <= u) {
mid = (int) ((l + u) / 2);
if (ns.compareTo(a[mid]) > 0) {
l = mid + 1;
} else if (ns.compareTo(a[mid]) < 0) {
u = mid - 1;
} else if (ns.compareTo(a[mid]) == 0) {
f = 1;
}
}
if (f == 1) {
System.out.println("Name is " + a[mid] + " aim is " + b[mid]);
} else {
System.out.println("Name Not Found");
}
}
}
The problem is that there is no output in terminal window. I can see the message of Enter name to be Searched
as well as when I'm typing a string and pressing enter. However nothing else is happening. Does anyone know what is wrong?
Upvotes: 1
Views: 72
Reputation: 17538
When a match is found, you are not exiting the loop. It is an infinite loop. Try this:
...
while(l<=u)
{
mid=(int) ((l+u)/2);
if(ns.compareTo(a[mid]) > 0)
{
l=mid+1;
}
else if(ns.compareTo(a[mid])<0)
{
u=mid-1;
}
else if(ns.compareTo(a[mid])==0)
{
f=1;
break; //<- add this statement
}
}
...
With this change, I get this output:
Enter name to be Searched
Gargi
Name is Gargi aim is Singer
Upvotes: 3