查找算法之-二分查找

这个实例给出了二叉搜索算法在9个元素的数组arr中查找某个目标值的过程

0 1 2 3 4 5 6 7 8
-7 3 5 8 12 16 23 33 55

例子1:查找目标值23

0 1 2 3 4 5 6 7 8
-7 3 5 8 12 16 23 33 55

步骤1:索引范围[0,9];索引first=0,last=9,mid=(0+9)/2=4

target=23>midValue=12;因为没有查找到匹配,修改fist=5,last=9

0 1 2 3 4 5 6 7 8
-7 3 5 8 12 16 23 33 55

步骤2:索引范围[5,9],索引fist=5,last=9,mid=(5+9)/2=7

target=23<midValue=33;因为没有找到匹配,修改first=5,last=7

0 1 2 3 4 5 6 7 8
-7 3 5 8 12 16 23 33 55

 步骤3:索引范围[5,7],索引first=5,last=7,mid=(5+7)/2=6

target=23==midValue=23,找到匹配元素,返回这个索引值

public static int binSearch(int arr[],int first,int last,int target) {
		int mid,midValue;
		
		//1.取住数组的中间位置
		//2.比较目标值和中间位置的值
		//a.目标>中间值  ---->在后半部分递归
		//b.目标值<中间值--->在前半部分递归
		//c.目标值==中间值-->找到了查找目标,返回这个元素的数组索引
		//3.如果first>=last--->终止查找返回-1
		
		while(first<last) {		
			mid=(first+last)/2;
			midValue=arr[mid];
			if(target==midValue) {				
				return mid;
			}else if(target<midValue) {
				last=mid;
			}else {
				first=mid+1;
			}
		}
		return -1;
	}

猜你喜欢

转载自blog.csdn.net/taotaobaobei/article/details/84302569