二分
二分
1 /** 2 * 二分法 3 * */ 4 public class ErFen { 5 6 /** 7 * @param args 8 */ 9 public static void main(String[] args) { 10 11 int[] nums = {10,20,30,40,50,60}; 12 int p = 30; 13 int start = 0; 14 int end = nums.length-1; 15 while(start <= end) { 16 //中间位置 17 int middle = (start + end) / 2; 18 //中间值 19 int middleValue = nums[middle]; 20 if(p == middleValue) { 21 System.out.println(middle); 22 return; 23 } else if (p < middleValue) { 24 end = middle - 1; 25 } else { 26 start = middle + 1; 27 } 28 } 29 } 30 31 }
二分查找详解:
二分查找只使用升序或降序排列好的数列中查找
int[] a ={10,20,30,40,50,60}
int start = 0; int end = a.length-1; int middle = ( start + end) / 2
start = 0; end = 5; middle = 2
查找 P = 30
int middleValue = a[ middle ];
if( p = middleValue ) OK !
查找 P = 20
if( p < middleValue ) end = middle - 1;
middleValue = a[ middle ] = a[2] = 30 20 < 30 end = 2 -1 = 1 middle = 0 + 1 / 2 = 0
middleValue = a[ 0 ] = 10 20 > 10 start= 0 + 1 = 1 middle = 1 + 1 / 2 = 1
middleValue = a[ 1 ] = 20 20 = 20 OK !
查找 P = 60
if( p > middleValue ) start = middle + 1;
50 > 30 start = 2 + 1 = 3 middle =( start + end ) / 2 = (3 + 5 )/ 2 = 4
middleValue = a[ 4 ] = 50 60 > 50 start = 3 + 1 = 4 middle = (4 + 5 ) / 2 = 4
start = 4 + 1 middle = ( 5 + 5 ) / 2 = 5
middleValue = a[5] = 60 OK !