Reputation: 71
I'm having a problem with my code. We're working on binary search, and I can't seem to get the right output whenever I input a number. We were given a list of 60 numbers already in order(external file), and whatever number we input, the program should search and return the position. If the number is not on the list, it should return a -1.
My code:
import java.io.*;
import java.util.*;
public class Prog489
{
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number to search for: ");
int search = scan.nextInt();
Scanner kbReader = new Scanner(new File("C:\\Users\\Guest\\Documents\\java programs\\Prog489\\Prog489.in"));
int[] num = new int[60];
int i = 0;
System.out.println(binarySearch(num, search));
while(kbReader.hasNextInt())
{
num[i++] = kbReader.nextInt();
}
}
private static int binarySearch(int[] num, int search)
{
int lb = 0;
int ub = num.length - 1;
while(lb<=ub)
{
int mid = (lb+ub)/2;
if(num[mid] == search)
{
return mid;
}
else if(search>num[mid])
{
lb=mid+1;
}
else
{
ub = mid-1;
}
}
return -1;
}
}
So the part with the return should only return -1 if the number is not on the list. But whenever I do enter a number on the list (such as 60), it still returns a -1. Everything compiles, so I'm not really sure what I'm missing, or if it's something really obvious that I'm forgetting. Could someone please help me identify the error? Any guidance/feedback is greatly appreciated.
Upvotes: 1
Views: 145
Reputation: 3298
Move the call to print the output of binarySearch
to after you populate the array:
int[] num = new int[60];
int i = 0;
while(kbReader.hasNextInt())
{
num[i++] = kbReader.nextInt();
}
System.out.println(binarySearch(num, search));
Upvotes: 2