二分查找:非递归实现和递归实现
二分查找
算法思想:又叫折半查找,要求待查找的序列有序。每次取中间位置的值与待查关键字比较,如果中间位置的值比待查关键字大,则在前半部分循环这个查找的过程,如果中间位置的值比待查关键字小,则在后半部分循环这个查找的过程。直到查找到了为止,否则序列中没有待查的关键字。
二分查找的前提是这个数组是有序的。
第一种:非递归实现:
package com.bjsxt.com;
public class TestDiGui {
public static void main(String[] args) {
int arr[]= {1,2,3,4,5,6,7,8,9};
int num=1;
System.out.println(fun(arr,num));
}
private static int fun(int[] arr, int num) {
int low=0;
int heigh=arr.length-1;
if(num<arr[0]||num>arr[arr.length-1]||low>heigh) {
System.out.println("本身就有错");
return -1;
}
while(low<=heigh) {
int mid= (low+heigh)/2;
if(num==arr[mid]) {
System.out.println("找到了"+mid);
return mid;
}else if(num<arr[mid]) {
heigh=mid-1;
}else {
low=mid+1;
}
}
return -1;
}
}
第二种:递归实现:
package com.bjsxt.com;
public class TestDiGui {
public static void main(String[] args) {
int arr[]= {1,2,3,4,5,6,7,8,9};
int num=1;
int low=0;
int heigh=arr.length-1;
System.out.println(fun(arr,num,low,heigh));
}
private static int fun(int[] arr, int num,int low,int heigh) {
if(num<arr[0]||num>arr[arr.length-1]||low>heigh) {
System.out.println("本身就有错");
return -1;
}
int mid= (low+heigh)/2;
if(num==arr[mid]) {
System.out.println("找到了"+mid);
return mid;
}else if(num<arr[mid]) {
return fun(arr,num,low,heigh-1);
}else {
return fun(arr,num,low+1,heigh);
}
}
}
问题:为什么在使用非递归实现的时候,第一个元素和最后一个元素涉及不到?
原因:里边while的条件是low<=heigh,而不是low<heigh.