The psuedocode for binary search is pretty basic. Here it is:
1. Set min = 0 and max = n-1 (where n is the index of the last item in the list)
2. Check if max < min (this signals that the number is not in the list)
3. Take a guess. Make the guess at (max + min) / 2
4. Check if the guess is right. If it is, you're good! If not:
5. If your guess was less than the target, set your min value to your guess + 1 (get rid of a half of bread)
6. If your guess was greater than the target, set your max to your guess - 1
7. Repeat step 2.
That's all there is to it. Here is a working example in Java. The list contains all the even numbers up to 20. So this could be used to determine if a number is even or not. If it is found, the number is even. If not, the number is odd. (Zero is not included).
Open Eclipse and go to File -> New ->Project and select Java project. Right click on the src folder and add a class named BinSearch,java. Make sure to check add main args in the options or paste the code exactly as follows. Right click and select run to run it.
public class BinSearch {
public static void main(String[] args) {
int[] x = {2,4,6,8,10,12,14,16,18,20};
int min = 0;
int max = x.length - 1;
int target = 6;
int guess = 0;
boolean searching = true;
while(searching)
{
if(max < min)
{
System.out.println("Not found");
searching = false;
}
guess = (int)Math.floor((max + min) / 2);
if(x[guess] == target)
{
System.out.println("Found");
searching = false;
}
if(x[guess] < target)
min = guess + 1;
else
max = guess - 1;
}
}
}
Here is a graphic showing the process visually:
No comments:
Post a Comment