1. Background
For example, an integer x is a set of numbers in a sequence of columns sorted by size, and we want to find the index position of x in the sequence.
For example, the sequence is arranged from small to large:
-3,-2,0,4,5,7,12,64
We want to find the position of the number 7, if it is a linear lookup, the time complexity is O (n), if you find with binary, the time complexity is O (log (n)), because each time the binary, the calculation of less than half, so take the logarithm.
2. Code
Package Algorithm_analysis;public class Bisearch {static int[] array={-3,-2,0,4,5,7,12,64}, public static void main ( String args[]) { int left=0; int right=array.length; int center=0; int k=7; while (left<=right) { center= (right+left)/2; if ((array[center]-k) ==0) { System.out.print (center); break; } else{ if ((array[center]-k) >0) { right=center; } else{ Left=center;}}}} Output Results 7
/********************************
* This article from the blog "Bo Li Garvin"
* Reprint Please indicate the source : Http://blog.csdn.net/buptgshengod
******************************************/
"Algorithm data structure Java implementation" binary lookup