package alg;
import java.util.Arrays;
/*
* 算法分析:
* 每执行一次search算法,查找的范围就小一半
* 假定有n个元素
* 当n=1时,查找一个元素需要常量时间T(n)=O(1);
* 当n>1时,T(n)=T(n/2)+O(1);
* T(n)=T(n/2)+O(1)
* =T(n/4)+2O(1)
* =T(n/2^3)+3O(1)
* =.....
* =T(n/2^n)+nO(1)
* 令n=2^x
* 则x=logn
* 所以T(n)=T(1)+logn=O(1)+O(logn) 故其空间复杂性为O(logn)
* */
public class Select
{
static int[] a={11,15,18,25,26,28,37};
public static int search(int a[],int x,int low,int high)
{
int middle=(low+high)/2;
if(x==a[middle])
return middle;
else if(x>a[middle])
{
return search(a,x,middle+1,high);
}
else if(x<a[middle])
{
return search(a,x,low,middle-1);
}
return -1;
}
public static void main(String[] args)
{
int x=search(a,26,0,a.length);
System.out.println(x);
}
}
二分查找算法
最新推荐文章于 2024-09-04 21:39:45 发布