Algorithm: It is suitable to use this method when the amount of data is large. when searching by binary method, the data need to be ordered and not duplicated . Basic idea: Assume that the data is sorted in ascending order, for a given value x, from the middle of the sequence of the comparison, if the current position value equals X, then the search succeeds; if x is less than the current position value, the first half of the sequence is searched, and if x is greater than the current position, the second half of the series is searched until
Suppose there is an array {
20,21,22,23,24,25,26,27
public class Twofindnum {public static void main (string[] args) {int []array=new int[]{20,21,22,23,24,25,26,27}; System.out.println (Search (array, 21)); If you find a value in an array, it returns the subscript for the element. otherwise returns-1. System.out.println (Search (array,30));} Two-point lookup public static int search (int []array,int key) {int Start=0;int end=array.length-1; Length starting from 0, last subscript minus 1while (start<end) {int mid= (start+end)/2;if (Key<array[mid]) end=mid-1;else if (key>array[ Mid]) {start=mid+1;} Else{return Mid;}} return-1;}}
This article is from the "Star Moon Love" blog, please be sure to keep this source http://xuegodxingyue.blog.51cto.com/5989753/1950461
Java Binary Lookup algorithm