/**
* Created by Leon on 2017/4/4.
* 二分搜索算法
*/
public class Binary_Search
{
public static void main(String[] args)
{
int srcArray[]={3,5,11,17,21,23,28,30,32,50,64,78,81,95,101};
System.out.println(binSearch(srcArray,0,srcArray.length-1,81));
System.out.println(binSearch(srcArray,81));
}
/**二分查找递归实现
* start起始下标,end结尾下标,key待查找数据
*/
public static int binSearch(int srcArray[],int start,int end,int key)
{
int mid=(end-start)/2+start;//中间下标
if(srcArray[mid]==key)
{
return mid;
}
if (start>=end)
{
return -1;
}else if(key>srcArray[mid])
{
return binSearch(srcArray,mid+1,end,key);
}else if (key<srcArray[mid])
{
return binSearch(srcArray,start,mid-1,key);
}
return -1;
}
/**二分查找普通循环实现
* start起始下标,end结尾下标,key待查找数据
*/
public static int binSearch(int srcArray[],int key)
{
int mid=srcArray.length/2;
if (key==srcArray[mid])
{
return mid;
}
int start=0;
int end=srcArray.length-1;
while (start<=end)
{
mid=(end-start)/2+start;
if (key<srcArray[mid])
{
end=mid-1;
}else if (key>srcArray[mid])
{
start=mid+1;
}else
{
return mid;
}
}
return -1;
}
}
/**
* Created by Leon on 2017/4/4.
* 分治算法
* 计算乘方
*/
public class Divide_Conquer
{
public static int power(int x,int n)
{
int result;
if(n == 1)
return x;
if( n % 2 == 0)
result = power(x, n/2) * power(x, n / 2);
else
result = power(x, (n+1) / 2) * power(x, (n-1) / 2);
return result;
}
public static void main(String[] args)
{
int x = 5;
int n = 3;
System.out.println("power("+x+","+n+") =" +power(5,3));
}
}