二分查找Java实现

39次阅读

共计 657 个字符,预计需要花费 2 分钟才能阅读完成。

public class BinSearch {

// 递归实现
public static int binSearch(int[]arr,int low,int high,int key){
if(low>high||key<arr[low]||key>arr[high]){
return -1 ;
}
int mid = low+(high-low) / 2;
if (arr[mid] < key) {
return binSearch(arr, mid + 1, high, key);
} else if (arr[mid] > key) {
return binSearch(arr, low, mid – 1, key);
} else {
return mid;
}
}

// 非递归循环实现
public static int binSearch1(int[]arr,int key){
int low=0;
int high=arr.length-1;

while(low<=high){
int mid=low+(high-low)/2;
if(arr[mid]>key){
low=mid+1;
}else if(arr[mid]<key){
high=mid-1;
}else{
return mid;
}
}
return -1;
}

public static void main(String[] args) {
int[] arr=new int[]{3,4,5,6,7,8};
System.out.println(binSearch(arr,0,arr.length-1,5));
System.out.println(binSearch1(arr,5));
}
}

正文完
 0