package Find;
//折半查找只能用于有序的顺序表
public class BinarySearch {
//递归算法
public static int binaryDiGuiSearch(int[] data,int low,int high,int x) {
if(low>high){
return -1;
}
int mid=(low+high)/2;
if(x==data[mid]){
return mid;
}else if(x<data[mid]){
return binaryDiGuiSearch( data,low,mid-1,x);
}else {
return binaryDiGuiSearch( data,mid+1,high,x);
}
}
//非递归算法
public static int binarySearch(int[] data,int n,int x){
int low=0,high=n-1,mid=0;
while(low<=high){
mid=(low+high)/2;
if(x==data[mid]) {
return mid;
}else if(x<data[mid]){
high=mid-1;
}else{
low=mid+1;
}
}
return -1;
}
public static void main(String[] args){
int[] data={1,2,3,4,5,6,7};
System.out.println(binaryDiGuiSearch(data,0,6,4));
System.out.println(binarySearch(data,7,4));
}
}