JAVA—二分查找法
二分查找过程:(只有有序序列才能使用二分查找法)
首先,假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。
代码实现:
public static void main(String[] args) {
int[] arr = {1,2,6,7,34,56,67};
int low = 0;
int high = arr.length - 1;
System.out.println("请输入你要查找的数");
int find = new Scanner(System.in).nextInt();
int index = search(arr,low, high, find);
if (index == -1){
System.out.println("没有这个数");
}else {
System.out.println("您要查找数的索引为:" + index);
}
}
private static int search(int[] arr, int low, int high, int find) {
int index = -1;
while (low <= high){
int mid = (low + high) / 2;
if (arr[mid] < find){
low = mid + 1;
}else if (arr[mid] > find){
high = mid - 1;
}else {
index = mid;
break;
}
}
return index;
}
使用递归方式的代码实现(了解即可)
public static void main(String[] args) {
int[] arr={1,2,3,4,5,6,7,8,9};
System.out.println("请输入要查找的数据");
int find = new Scanner(System.in).nextInt();
int index=binarySearch(arr,8,0,arr.length-1);
System.out.println(index);
}
public static int binarySearch(int[] arr,int find,int low,int high){
if(low>high){
return -1;
}
int mid=(low+high)/2;
int guess=arr[mid];
if(guess>find){
return binarySearch(arr,find,low,mid-1);
}else if(guess==find){
return mid;
}else{
return binarySearch(arr,find,mid+1,high);
}
}