废话少说,看代码
public static void main(String[] args) {
//二分查找:有多个相同的值时只查出现的第一个,立刻停止查找
//查到了返回下标
//普通查找
int arr[]={1,2,3,4,5};
int index = Search(arr, 4);
System.out.println(index);
//二分查找
int arr1[]={1,2,3,4,5,16,28,44,56,66,128};
int index1=ErFenSearch(arr1, 66);
System.out.println(index1);
}
//普通查找
public static int Search(int []arr,int key){
for(int i=0;i<arr.length;i++){
if(key==arr[i]){
return i;
}
}
return -1;
}
//二分查找
public static int ErFenSearch(int []arr,int key){
Search(arr,70)
int max=arr.length -1;
int min =0;
while(min<=max){
int mid =(max+min)/2; //int mid =(max+min) >>1;
if(arr[mid] == key){
return mid;
}else if(arr[mid]>key){
max=mid-1;
}else if(arr[mid]<key){
min=mid+1;
}
}
return -1;
}