二分法

package com.yh.day02.arrays;

public class Test01 {
public static void main(String[] args) {
int []a=new int[]{10,11,2,13,1,4,15,16,17,18,19};
int sy=binarySearch(a,17);
System.out.println(sy);
}

public static int binarySearch(int [] a,int key) {
int beginPost=0;
int endPost=a.length-1;
while(beginPost <= endPost){
int middlePost=(beginPost+endPost)/2;
if(a[middlePost]==key){
return middlePost;
}else if(a[middlePost] < key){
beginPost=middlePost+1;
}else{
endPost=middlePost-1;
}
}
return -1;



}
}

 

二分法_第1张图片

你可能感兴趣的:(二分法)