Binary searches search through an array by dividing a range of values into halves. It also a method called divide and conquer, which will continue to divide the data in half to narrow down the values to search. I created an earlier program where the user tries to guess a computer generate number and that uses similar methods to tell the user if they need to guess higher or lower. The binary search always begins at the middle of the set of values and then it will check if the value it's trying to find is greater or less than that value. Binary search is more efficient then linear search, but it has to be sorted (numbers in order) beforehand. If there are many values, it is more efficient to order the list with a sorting algorithm.
public class BinarySearch {
public static void main (String [] args){
int []val = {1,2,3,4,5,6,7,8,10};
System.out.println(binarysearch(val,4));
}
public static int binarysearch (int values[ ], int x ){
int low = 0; // first value
int high = values.length-1; // last value
while ( low <= high){
int midpoint = (low + high) /2; // int divison, take lower
if (values[midpoint] == x) // checks if equal to, less than, or greater to
return midpoint;
else if (values[midpoint] > x) // new high is index before the midpoint
high = midpoint - 1;
else if (values[midpoint] < x)
low = midpoint + 1; // new high is index after the midpoint
System.out.println(midpoint);
}
return -1; // returns if number isn't found in the array
}
}
4
1
2
3